<?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 Daniel Alfocea on Medium]]></title>
        <description><![CDATA[Stories by Daniel Alfocea on Medium]]></description>
        <link>https://medium.com/@cr0hn?source=rss-e88f464b9d9c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BIupcA-M94-RzqX99L5Viw@2x.jpeg</url>
            <title>Stories by Daniel Alfocea on Medium</title>
            <link>https://medium.com/@cr0hn?source=rss-e88f464b9d9c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:23:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cr0hn/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[The language tax: how much more you pay to use an LLM in Spanish (and why)]]></title>
            <link>https://cr0hn.medium.com/the-language-tax-how-much-more-you-pay-to-use-an-llm-in-spanish-and-why-096b0bb506dd?source=rss-e88f464b9d9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/096b0bb506dd</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[tokenization]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Daniel Alfocea]]></dc:creator>
            <pubDate>Mon, 23 Nov 2026 11:30:41 GMT</pubDate>
            <atom:updated>2026-11-23T11:30:41.785Z</atom:updated>
            <content:encoded><![CDATA[<p>The same 1,012 sentences through 16 tokenizers and 25 languages: Spanish costs 26% to 69% more than English.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cABsv16p7guXTy_y.png" /></figure><p>If your application talks to a language model in Spanish, you pay more than if it talked in English. Not a little more: with o200k, GPT-4o&#39;s tokenizer, the same sentence costs 32% more in Spanish. With DeepSeek&#39;s, 50% more. With Kimi&#39;s, 69% more. A $100 monthly bill in English is $132, $150 or $169 in Spanish, depending on who you pay. And nobody puts it on the pricing page, because the pricing page is per million tokens and doesn&#39;t say how many tokens your sentences are.</p><p>I wanted to know where that surcharge comes from, so I took the same corpus of 1,012 human-translated sentences (FLORES-200), ran it through the tokenizers of eight model families and counted. Then I repeated the count with 23 more languages besides English and Spanish, because anyone reading this in English also has users who write in Hindi, Portuguese or Japanese.</p><p>There are two culprits, and it pays to separate them, because one can’t be fixed and the other can. Written Spanish is 19% longer than English: you pay that with any model in the world and it isn’t going to change. The rest, anywhere from 7% to 50% depending on the tokenizer, is that the model’s chopper learned from far more English than Spanish and cuts our words into more pieces. That does change, and it changes a lot between providers and between generations of the same provider.</p><p>A word on tone: there are wide tables and figures with three decimals, but there is also a tokenizer that needs seven tokens to write “¿Cómo estás?”, and that deserves a comment.</p><h4>What I measured and what I didn’t</h4><p>Everything below comes from counting tokens myself, on October 31, 2026, with the tokenizer files each lab publishes on Hugging Face or in its libraries, pinned to a specific revision. There isn’t a single figure from memory or from an X thread. Prices are the list prices on each provider’s official page that day, in dollars per million tokens, and I use them as they are.</p><ul><li><strong>Actually measured</strong>: the tokenizers of OpenAI (o200k_base, used by GPT-4o and gpt-oss, and cl100k_base, used by GPT-4 and the original ChatGPT), DeepSeek (V3.2 and V4.1-Flash), Mistral (Small 3.2 and Large 4), Qwen (Qwen3-8B and Qwen3.8), Meta (Llama 3.3 and Llama 4 Scout), Google (Gemma 3 and Gemma 4), Z.ai (GLM-4.6 and GLM-5.3) and Moonshot (Kimi K2 and K3). Sixteen files, although several give identical counts and I say so when it happens.</li><li><strong>Not measured</strong>: Claude and Gemini. Anthropic and Google don’t publish the tokenizer of their API models; the only way to count is to call their token-counting API, and I had no key for that. For Gemini there’s a reasonable approximation that I explain below; for Claude, none I’d dare sign.</li><li><strong>What I don’t use even though I’ve seen it</strong>: Mistral’s prices, because I found two different figures for Mistral Large on two official pages and couldn’t work out which applies. I give its token ratio, which is what I measured, and not its dollars.</li></ul><p>The corpus is the FLORES-200 <em>devtest</em>: 1,012 sentences taken from Wikinews, Wikibooks and Wikivoyage and translated by human translators into more than 200 languages, the same sentence in all of them. It’s the corpus used by the reference paper on this topic, Petrov et al. at NeurIPS 2023 (they used 2,000 FLORES-200 sentences; I used the 1,012 of the <em>devtest</em>), and that lets me check that my measurement matches theirs: they got 1.55 for Spanish with ChatGPT’s tokenizer; I get 1.544. That reassures me about the method, so on to what matters.</p><h4>The count: how much more you pay in Spanish</h4><p>I’ll start with the table everyone wants to see. The “ES/EN” column is how many tokens it takes in Spanish for every token it takes in English to say the same thing, over the full 1,012 sentences. The confidence intervals come from a <em>bootstrap</em> of 10,000 resamples over the sentences, including for Mistral Large 4 and Qwen3.8. They help separate noise from signal: the five in the 1.30–1.34 zone (Gemma 3, Llama 4, Mistral Small 3.2, o200k and Qwen3.8) have overlapping intervals and can&#39;t be told apart with this corpus; Mistral Large 4 sits below all of them, with a separate interval; between that zone and GLM, DeepSeek, cl100k or Kimi, the gap is many times the interval.</p><ul><li><strong>Mistral</strong>: Tokenizer Large 4 (Tekken) · EN tokens 27,831 · ES tokens 34,965 · ES/EN <strong>1.256</strong> · 95% CI [1.245, 1.268]</li><li><strong>Google</strong>: Tokenizer Gemma 3 · EN tokens 27,114 · ES tokens 35,167 · ES/EN <strong>1.297</strong> · 95% CI [1.284, 1.310] · Same count as Gemma 4 (12B and 31B)</li><li><strong>Meta</strong>: Tokenizer Llama 4 Scout · EN tokens 27,048 · ES tokens 35,113 · ES/EN <strong>1.298</strong> · 95% CI [1.286, 1.311]</li><li><strong>Mistral</strong>: Tokenizer Small 3.2 (Tekken) · EN tokens 27,827 · ES tokens 36,657 · ES/EN <strong>1.317</strong> · 95% CI [1.304, 1.331]</li><li><strong>OpenAI</strong>: Tokenizer o200k_base · EN tokens 26,873 · ES tokens 35,415 · ES/EN <strong>1.318</strong> · 95% CI [1.305, 1.331] · Same count as gpt-oss-120b ✱, o200k_harmony</li><li><strong>Qwen</strong>: Tokenizer Qwen3.8 · EN tokens 27,530 · ES tokens 36,423 · ES/EN <strong>1.323</strong> · 95% CI [1.310, 1.337] · Same count as Qwen3.8–27B ✱, Flash-Next ✱</li><li><strong>Z.ai</strong>: Tokenizer GLM-5.3 · EN tokens 27,185 · ES tokens 39,188 · ES/EN <strong>1.442</strong> · 95% CI [1.426, 1.457] · Same count as GLM-4.6, 5.1 ✱, 5.2 ✱</li><li><strong>DeepSeek</strong>: Tokenizer V4.1-Flash-1017 · EN tokens 27,041 · ES tokens 40,434 · ES/EN <strong>1.495</strong> · 95% CI [1.480, 1.511] · Same count as V3.2, V4-Pro-0813 ✱</li><li><strong>Qwen</strong>: Tokenizer Qwen3 (8B, 2025) · EN tokens 27,621 · ES tokens 42,051 · ES/EN <strong>1.522</strong> · 95% CI [1.506, 1.539]</li><li><strong>Meta</strong>: Tokenizer Llama 3.3 · EN tokens 27,171 · ES tokens 41,885 · ES/EN <strong>1.542</strong> · 95% CI [1.525, 1.558]</li><li><strong>OpenAI</strong>: Tokenizer cl100k_base (GPT-4) · EN tokens 27,182 · ES tokens 41,974 · ES/EN <strong>1.544</strong> · 95% CI [1.528, 1.561]</li><li><strong>Moonshot</strong>: Tokenizer Kimi K3 · EN tokens 27,137 · ES tokens 45,842 · ES/EN <strong>1.689</strong> · 95% CI [1.672, 1.708] · Same count as K2, K2.6 ✱, K2.7-Code ✱</li></ul><p>✱ Checked separately, by file hash or by counting by hand; reproduce.py doesn&#39;t measure these tokenizers, so this match can&#39;t be reproduced with the published script. The others can.</p><p>Three things jump out.</p><p>The first: <strong>the range runs from 1.26 to 1.69</strong>. Between the best tokenizer for Spanish and the worst there are 43 percentage points of difference in what you pay for the same sentence. That’s more than the list-price gap between many competing models.</p><p>The second: <strong>every lab that has renewed its tokenizer has improved Spanish</strong>, and not by a little. OpenAI went from 1.544 (cl100k) to 1.318 (o200k). Meta, from 1.542 (Llama 3.3) to 1.298 (Llama 4). Qwen, from 1.522 to 1.323 between Qwen3 and Qwen3.8. The three jumps are almost the same: from &quot;50% more&quot; to &quot;30% more&quot;. What changed I cover in the why section; I&#39;ll say up front that Google and Mistral do say what they did with theirs, and that for OpenAI, Meta and Qwen what I give is my interpretation.</p><p>The third: <strong>some labs’ tokenizers have behaved the same, in this corpus, for several generations</strong>, and it shows. Kimi K3’s file is, byte for byte, the same as Kimi K2’s (same SHA-256 hash). DeepSeek changed the file between V3.2 and V4.1, but the measured behavior doesn’t change: the counts come out identical down to the last token, in English and in Spanish. GLM-5.1, 5.2 and 5.3 share a file (I checked 5.1 and 5.2 separately, outside the script), and GLM-4.6 has a different one that counts exactly the same. A model being from 2026 doesn’t mean its tokenizer is.</p><h4>In dollars</h4><p>A ratio is abstract; a bill isn’t. This table applies the ratio to each model’s list price. The reading is: “what a million tokens costs in English gets charged to you as if it were 1.3 or 1.5 or 1.7 million when the text is in Spanish”. The right-hand column is a sample job with a million input tokens and a million output tokens, counted in English, and what that same job costs when the text is in Spanish.</p><ul><li><strong>DeepSeek </strong><strong>deepseek-flash (0.30 / 1.20, peak rate)</strong>: Tokenizer used V4.1-Flash-1017 (its own) · ES/EN 1.495 · Effective input in ES 0.45 · Effective output in ES 1.79 · 1M+1M job: EN → ES $1.50 → $2.24 (+0.74)</li><li><strong>DeepSeek </strong><strong>deepseek-v4-pro (1.32 / 3.96, peak)</strong>: Tokenizer used V4-Pro-0813 (its own) · ES/EN 1.495 · Effective input in ES 1.97 · Effective output in ES 5.92 · 1M+1M job: EN → ES $5.28 → $7.90 (+2.62)</li><li><strong>Z.ai GLM-5.3 (1.40 / 4.40)</strong>: Tokenizer used GLM-5.3 (its own) · ES/EN 1.442 · Effective input in ES 2.02 · Effective output in ES 6.34 · 1M+1M job: EN → ES $5.80 → $8.36 (+2.56)</li><li><strong>Moonshot </strong><strong>kimi-k3 (3.00 / 15.00)</strong>: Tokenizer used Kimi K3 (its own) · ES/EN 1.689 · Effective input in ES 5.07 · Effective output in ES 25.34 · 1M+1M job: EN → ES $18.00 → $30.41 (+12.41)</li><li><strong>Alibaba </strong><strong>qwen3.8-max (2.00 / 6.00)</strong>: Tokenizer used Qwen3.8 ⁽¹⁾ · ES/EN 1.323 · Effective input in ES 2.65 · Effective output in ES 7.94 · 1M+1M job: EN → ES $8.00 → $10.58 (+2.58)</li><li><strong>OpenAI GPT-6 Luna (0.10 / 0.50)</strong>: Tokenizer used o200k_base ⁽²⁾ · ES/EN 1.318 · Effective input in ES 0.13 · Effective output in ES 0.66 · 1M+1M job: EN → ES $0.60 → $0.79 (+0.19)</li><li><strong>OpenAI GPT-6.1 Sol (2.00 / 10.00)</strong>: Tokenizer used o200k_base ⁽²⁾ · ES/EN 1.318 · Effective input in ES 2.64 · Effective output in ES 13.18 · 1M+1M job: EN → ES $12.00 → $15.81 (+3.81)</li><li><strong>OpenAI GPT-6 Astra (10.00 / 50.00)</strong>: Tokenizer used o200k_base ⁽²⁾ · ES/EN 1.318 · Effective input in ES 13.18 · Effective output in ES 65.90 · 1M+1M job: EN → ES $60.00 → $79.07 (+19.07)</li><li><strong>Google </strong><strong>gemini-3.8-flash (0.75 / 3.75 until Dec 31, 2026)</strong>: Tokenizer used Gemma 3 ⁽³⁾ · ES/EN ≈1.297 · Effective input in ES ≈0.97 · Effective output in ES ≈4.86 · 1M+1M job: EN → ES $4.50 → ≈$5.84 (+1.34)</li><li><strong>Google </strong><strong>gemini-3.8-flash (1.50 / 7.50 from Jan 1, 2027)</strong>: Tokenizer used Gemma 3 ⁽³⁾ · ES/EN ≈1.297 · Effective input in ES ≈1.95 · Effective output in ES ≈9.73 · 1M+1M job: EN → ES $9.00 → ≈$11.67 (+2.67)</li><li><strong>Google </strong><strong>gemini-4-argon (2.00 / 10.00 until Nov 30, 2026)</strong>: Tokenizer used Gemma 3 ⁽³⁾ · ES/EN ≈1.297 · Effective input in ES ≈2.59 · Effective output in ES ≈12.97 · 1M+1M job: EN → ES $12.00 → ≈$15.56 (+3.56)</li><li><strong>Google </strong><strong>gemini-4-argon (4.00 / 20.00 from Dec 1, 2026)</strong>: Tokenizer used Gemma 3 ⁽³⁾ · ES/EN ≈1.297 · Effective input in ES ≈5.19 · Effective output in ES ≈25.94 · 1M+1M job: EN → ES $24.00 → ≈$31.13 (+7.13)</li></ul><p>⁽¹⁾ The file I measured is Qwen3.8–2.4T-A95B’s, identical to Qwen3.8–27B’s and Flash-Next’s (checked separately, outside reproduce.py). I haven&#39;t checked that qwen3.8-max shares the file; I assume the family goes together, and if it doesn&#39;t, the row is wrong. ⁽²⁾ OpenAI doesn&#39;t publish which tokenizer the GPT-6 models use over the API. o200k_base is the latest it has published for its API models (GPT-4o); gpt-oss uses o200k_harmony, a later variant with the same counts. If GPT-6 uses another, these rows change. It&#39;s the most reasonable hypothesis I have, and it is a hypothesis. ⁽³⁾ Google says in the Gemma 3 technical report that it uses &quot;the same tokenizer as Gemini 2.0&quot;. Gemini 3.8 and 4 are not Gemini 2.0, so this is an approximation two generations removed. Google&#39;s pricing page, read on October 31, 2026, announced the two increases shown in the table: gemini-4-argon goes to 4.00 / 20.00 on December 1, 2026 and gemini-3.8-flash to 1.50 / 7.50 on January 1, 2027, before this article is published. The newer rows are the ones you&#39;ll be charged.</p><p>Two readings of this table before moving on. One: the absolute surcharge is driven by price, not by ratio. Kimi K3 has the worst ratio for Spanish and is also expensive, so the sample job costs it $12 more in Spanish than in English; for GPT-6 Luna, with a middling ratio and a very low price, the same surcharge costs 19 cents. Two: when you compare two models of similar price, the tokenizer can be the difference between them. qwen3.8-max and GPT-6.1 Sol cost the same on input in English ($2) and practically the same in Spanish (2.65 against 2.64), because their tokenizers treat Spanish almost identically. GLM-5.3 costs 1.40 on input in English and 2.02 in Spanish; in Spanish it gets close to what the other two cost in English.</p><p>A warning that holds for the whole table: FLORES is text from Wikinews, Wikibooks and Wikivoyage translated by humans. What the model sends back in Spanish may be more or less wordy than a human translation, and what you send it may be JSON, code or an English system prompt, none of which pays the surcharge. These ratios are for text in Spanish; how much of your traffic is text in Spanish, you know.</p><h4>Where the surcharge comes from: two culprits</h4><p>This is the part of the exercise I found most useful. The surcharge in the table above can be split into two factors that multiply, and both can be measured.</p><p><strong>The first is that Spanish is longer.</strong> The 1,012 sentences take up 131,966 characters in English and 157,041 in Spanish: 19.0% more. In words the same happens (21,901 against 26,081, 19.1% more). In this corpus and with these translators that’s how it is, and the underlying reason is the usual one: “the” is three letters, while Spanish brings “el”, “la”, “los”, “las” along with prepositions and agreements that English doesn’t have. Every tokenizer pays this, even a perfect one, and no provider can do anything about it.</p><p><strong>The second is that the tokenizer chops Spanish up worse.</strong> If a tokenizer were equally efficient in both languages, the token ratio would be 1.19, the same as the character ratio. Everything above 1.19 is the tokenizer. Dividing the token ratio by 1.19 gives the <strong>pure tokenizer penalty</strong>: how many more pieces it makes per character in Spanish than in English. A note on the unit: here I measure length in characters; if I measure it in UTF-8 bytes, Spanish is 21.1% longer (the accents and the eñe take two bytes) and the penalty comes out somewhat smaller (1.088 instead of 1.107 for o200k). Both are correct, they say different things, and I state which one I use in each table: characters in this section, bytes in the 25-language one.</p><ul><li><strong>Mistral Large 4</strong>: ES/EN tokens 1.256 · Total surcharge +25.6 pts · From length +19.0 · From tokenizer +6.6 · Pure penalty 1.056</li><li><strong>Gemma 3 / 4</strong>: ES/EN tokens 1.297 · Total surcharge +29.7 · From length +19.0 · From tokenizer +10.7 · Pure penalty 1.090</li><li><strong>Llama 4 Scout</strong>: ES/EN tokens 1.298 · Total surcharge +29.8 · From length +19.0 · From tokenizer +10.8 · Pure penalty 1.091</li><li><strong>Mistral Small 3.2</strong>: ES/EN tokens 1.317 · Total surcharge +31.7 · From length +19.0 · From tokenizer +12.7 · Pure penalty 1.107</li><li><strong>o200k_base</strong>: ES/EN tokens 1.318 · Total surcharge +31.8 · From length +19.0 · From tokenizer +12.8 · Pure penalty 1.107</li><li><strong>Qwen3.8</strong>: ES/EN tokens 1.323 · Total surcharge +32.3 · From length +19.0 · From tokenizer +13.3 · Pure penalty 1.112</li><li><strong>GLM-5.3</strong>: ES/EN tokens 1.442 · Total surcharge +44.2 · From length +19.0 · From tokenizer +25.2 · Pure penalty 1.211</li><li><strong>DeepSeek V4.1</strong>: ES/EN tokens 1.495 · Total surcharge +49.5 · From length +19.0 · From tokenizer +30.5 · Pure penalty 1.257</li><li><strong>Qwen3 (2025)</strong>: ES/EN tokens 1.522 · Total surcharge +52.2 · From length +19.0 · From tokenizer +33.2 · Pure penalty 1.279</li><li><strong>Llama 3.3</strong>: ES/EN tokens 1.542 · Total surcharge +54.2 · From length +19.0 · From tokenizer +35.2 · Pure penalty 1.295</li><li><strong>cl100k_base</strong>: ES/EN tokens 1.544 · Total surcharge +54.4 · From length +19.0 · From tokenizer +35.4 · Pure penalty 1.298</li><li><strong>Kimi K3</strong>: ES/EN tokens 1.689 · Total surcharge +68.9 · From length +19.0 · From tokenizer +49.9 · Pure penalty 1.420</li></ul><p>(The “from length” and “from tokenizer” points add up to the total surcharge; the tokenizer part is 1.19 × (penalty − 1), which is why it doesn’t match the bare penalty.)</p><p>With Mistral Large 4, of every 25 cents of surcharge, 19 are the language and 6 the tokenizer: almost all of it is unavoidable. With Kimi K3, of every 69 cents, 19 are the language and 50 the tokenizer: almost all of it is avoidable, and in fact others avoid it. In the middle, with o200k, the split is 19 and 13: the tokenizer is 40% of the surcharge.</p><h4>What that looks like in words</h4><p>The pure penalty has a visual translation: how many ordinary words fit in a single token. Among the thousand most frequent words of each language in the 1,012 sentences, I counted how many come out as a single token (with their leading space). This count is from the first pass, so for GLM, DeepSeek and Kimi the file is GLM-4.6’s, DeepSeek-V3.2’s and Kimi K2’s, which count the same as the current ones. In English all the tokenizers sit between 93% and 96%. In Spanish:</p><ul><li><strong>Gemma 3</strong>: 95.9% · 88.4%</li><li><strong>Llama 4 Scout</strong>: 94.2% · 87.0%</li><li><strong>o200k_base</strong>: 95.3% · 86.3%</li><li><strong>Mistral Small 3.2</strong>: 93.0% · 82.5%</li><li><strong>GLM-4.6 (= 5.3)</strong>: 94.4% · 69.7%</li><li><strong>DeepSeek V3.2 (= V4.1)</strong>: 93.2% · 59.7%</li><li><strong>Qwen3 (2025)</strong>: 94.4% · 53.5%</li><li><strong>Llama 3.3</strong>: 94.4% · 51.1%</li><li><strong>cl100k_base</strong>: 94.4% · 51.0%</li><li><strong>Kimi K2 (= K3)</strong>: 93.5% · 26.0%</li></ul><p>For Kimi, three out of four frequent Spanish words have no token of their own. With cl100k, half. And then there are the specific cases, which is where you see what&#39;s going on:</p><ul><li><strong>information</strong>: o200k 1 · Gemma 3 1 · Mistral L4 1 · DeepSeek 1 · Qwen3.8 1 · Kimi K3 1 · GLM-5.3 1</li><li><strong>información</strong>: o200k inform\|ación (2) · Gemma 3 2 · Mistral L4 2 · DeepSeek 2 · Qwen3.8 2 · Kimi K3 2 · GLM-5.3 2</li><li><strong>development</strong>: o200k 1 · Gemma 3 1 · Mistral L4 1 · DeepSeek 1 · Qwen3.8 1 · Kimi K3 1 · GLM-5.3 1</li><li><strong>desarrollo</strong>: o200k des\|arrollo (2) · Gemma 3 des\|ar\|rollo (3) · Mistral L4 3 · DeepSeek 2 · Qwen3.8 3 · Kimi K3 3 · GLM-5.3 2</li><li><strong>aprendizaje</strong>: o200k apr\|endiz\|aje (3) · Gemma 3 aprendizaje (1) · Mistral L4 3 · DeepSeek ap\|rend\|iz\|aje (4) · Qwen3.8 4 · Kimi K3 4 · GLM-5.3 3</li><li><strong>también</strong>: o200k tamb\|ién (2) · Gemma 3 1 · Mistral L4 2 · DeepSeek t\|amb\|ién (3) · Qwen3.8 2 · Kimi K3 3 · GLM-5.3 2</li><li><strong>año</strong>: o200k a\|ño (2) · Gemma 3 año (1) · Mistral L4 2 · DeepSeek 2 · Qwen3.8 2 · Kimi K3 2 · GLM-5.3 2</li><li><strong>¿Cómo estás?</strong>: o200k ¿Cómo\| estás\|? (3) · Gemma 3 4 · Mistral L4 3 · DeepSeek 5 · Qwen3.8 4 · Kimi K3 ¿\|C\|ó\|mo\| est\|ás\|? (7) · GLM-5.3 4</li></ul><p>“Information” and “development” are one token in all of them. “Información” and “desarrollo” are not in any. “Año”, one of the most frequent words in the language, is two tokens in all but Gemma, and the cut falls right at the eñe. And Kimi needs seven tokens for “¿Cómo estás?”: “Cómo” comes out in three pieces, C, ó and mo, with the cut on either side of the accented vowel. That the &quot;ó&quot; is the cause is my reading of the splitting, not something I could check in the vocabulary.</p><p>It also has to be said that the ratio is an average and varies a lot sentence by sentence. Of the three median-length sentences I looked at in detail, one (about consulting other governments’ advice) comes out <em>shorter</em> in Spanish than in English in four of the eight tokenizers (in three of them, 20 tokens against 24, ratio 0.83) because the translator was more concise than the original. Another, with “honeymoon” and some guillemets, comes out at 1.70 with Kimi and 1.28 with Gemma. The median of the sentence-by-sentence ratios sits right next to the global ratio in every tokenizer (1.313 against 1.318 for o200k, for example), so the average is representative, but a particular sentence can be far off.</p><h4>Why the tokenizer chops Spanish up worse</h4><p>So far, the measurement. Now the mechanism, which is what lets you predict what will happen with the next model.</p><h4>BPE: a compressor that learns from what it sees</h4><p>Almost all the tokenizers in the table are variants of <em>Byte Pair Encoding</em>. The algorithm comes from a 1994 compression paper and was adapted to machine translation by Sennrich et al. in 2016, who describe it like this: “Byte Pair Encoding (BPE) […] is a simple data compression technique that iteratively replaces the most frequent pair of bytes in a sequence with a single, unused byte”. Instead of bytes, they merge characters: “Instead of merging frequent pairs of bytes, we merge characters or character sequences”.</p><p>The idea fits in one sentence: you start with single characters, look in a training corpus for which pair of adjacent symbols appears most often, merge it into a new symbol, and repeat tens of thousands of times until you have a vocabulary of the size you want. What shows up a lot in that corpus ends up as a whole token; what shows up little stays chopped into smaller pieces.</p><p>The consequence is direct: <strong>the tokenizer is a statistical portrait of the corpus it was trained on</strong>. If the corpus was 90% English, “information” will get its own token and “información” won’t, not because of any property of Spanish, but because the algorithm saw “information” a hundred times more.</p><h4>What they were trained on</h4><p>Labs don’t publish the exact tokenizer corpus, but they do give clues. GPT-2, the grandfather of cl100k and o200k, was trained on WebText, and in their own paper the authors say that when filtering the corpus they found only 10 MB of French. GPT-2&#39;s tokenizer had 50,257 entries and, according to Petrov&#39;s table, gave Spanish a ratio of 1.99: twice the tokens of English.</p><p>Llama 2 published the language distribution of its pretraining data (table 10 of the paper): English 89.70%, “unknown” 8.38%, German 0.17%, French 0.16%, Chinese 0.13% and Spanish 0.13%. The table’s legend clarifies that “the large unknown category is partially made up of programming code data”. It isn’t the tokenizer corpus, but it gives an idea of the family’s diet. And the web in general, which is where nearly everything comes from: in the Common Crawl statistics for the CC-MAIN-2026–43 capture, 42.6% of HTML pages are in English, 4.7% in Spanish, 4.4% in Chinese, 2.5% in Portuguese, 0.21% in Hindi and 0.04% in Tamil. (These are pages, not text, and detection is done by CLD2; the page itself warns about this.)</p><p>With those percentages, a BPE trained “on the web” without rebalancing will have between eight and ten times more material in English than in Spanish, and a thousand times more than in Tamil. English takes the tokens.</p><p>This also explains, I think, the jump in the newer tokenizers. What changed between cl100k and o200k, between Llama 3 and Llama 4, between Qwen3 and Qwen3.8, is the vocabulary; that the language mix of the tokenizer corpus also changed is my interpretation in those three cases, because OpenAI, Meta and Qwen don&#39;t say. Google and Mistral do. Google says it explicitly in the Gemma 3 technical report: &quot;We use the same tokenizer as Gemini 2.0: a SentencePiece tokenizer with split digits, preserved whitespace, and byte-level encodings (Kudo and Richardson, 2018). The resulting vocabulary has 262k entries. This tokenizer is more balanced for non-English languages&quot;. Mistral, when presenting Tekken in 2024, said it compresses text &quot;more efficiently than the SentencePiece tokenizer used in previous Mistral models&quot;, and that it is &quot;~30% more efficient at compressing source code, Chinese, Italian, French, German, Spanish, and Russian&quot;: that 30% is against its previous SentencePiece, not against Llama 3. Against Llama 3 it only says Tekken &quot;proved to be more proficient in compressing text for approximately 85% of all languages&quot;, with no per-language figure. It&#39;s a vendor claim with no published methodology. I can&#39;t check the 30%, because I haven&#39;t measured Mistral&#39;s earlier tokenizer. What I can compare is Llama 3: the Tekken I measured is Mistral Small 3.2&#39;s, and in Spanish it uses 12.5% fewer tokens than Llama 3.3 (36,657 against 41,885). That&#39;s consistent with Mistral&#39;s &quot;more efficient&quot;, though it says nothing about that 30%.</p><p>Petrov et al. already warned in 2023 that this isn’t fixed by good intentions alone: “These disparities persist even for tokenizers that are intentionally trained for multilingual support”. Their paper defines a language’s “premium” exactly as I’ve used it here: “The ratio |t(sA)|/|t(sB)| is the premium for A relative to B”, with sA and sB the same sentence in the two languages. And they measured differences “up to 15 times in some cases” between languages. In parallel, Ahia et al. (arXiv 2305.13707, May 2023) laid out the economic consequence just as clearly: “speakers of a large number of the supported languages are overcharged while obtaining poorer results”, with “some languages requiring 5 times as many tokens than others”.</p><h4>UTF-8: the eñe costs double</h4><p>There’s a third layer, lower down, that mostly affects languages that don’t use the Latin alphabet but also brushes Spanish. Modern tokenizers work on bytes, not characters: GPT-2 introduced this because “a byte-level version of BPE only requires a base vocabulary of size 256”, and so any text in the world can be encoded with no unknown characters. It’s an elegant decision with a price: an ASCII letter is one byte, but “ñ”, “á”, “é”, “í”, “ó”, “ú” and “ü” are two bytes in UTF-8, and so is a Cyrillic, Arabic or Hebrew letter; a Devanagari or Tamil one, three; a Chinese or Japanese ideogram, three.</p><p>For Spanish the effect is small but measurable: the 1,012 sentences are 19.0% longer in characters and 21.1% longer in bytes. Those two points are the accents and the eñes. What the data shows is that “año” comes out as a + ño in every tokenizer except Gemma: two tokens, with the cut right before the eñe, and the pieces are whole characters, not loose bytes. Whether the two bytes of the &quot;ñ&quot; have anything to do with that cut is my hypothesis; what I know is that the cut is there. For Hindi or Tamil the effect is enormous, and it&#39;s what explains the figures in the next section.</p><h4>The other 23 languages</h4><p>I repeated the measurement with 25 FLORES-200 languages, with the same 1,012 sentences in each, and with the ten tokenizers that cover the families above. The table is wide; on a phone, it scrolls. It’s sorted by the o200k column, and the value is the token ratio relative to English.</p><ul><li><strong>English</strong>: o200k 1.000 · cl100k 1.000 · Gemma 3 1.000 · Mistral L4 1.000 · DeepSeek V4.1 1.000 · Qwen3 (2025) 1.000 · Qwen3.8 1.000 · Kimi K3 1.000 · GLM-5.3 1.000 · Llama 4 1.000</li><li><strong>Portuguese</strong>: o200k 1.225 · cl100k 1.478 · Gemma 3 1.257 · Mistral L4 1.156 · DeepSeek V4.1 1.423 · Qwen3 (2025) 1.452 · Qwen3.8 1.241 · Kimi K3 1.616 · GLM-5.3 1.404 · Llama 4 1.225</li><li><strong>Dutch</strong>: o200k 1.247 · cl100k 1.603 · Gemma 3 1.383 · Mistral L4 1.183 · DeepSeek V4.1 1.497 · Qwen3 (2025) 1.591 · Qwen3.8 1.380 · Kimi K3 1.688 · GLM-5.3 1.517 · Llama 4 1.331</li><li><strong>Chinese (simpl.)</strong>: o200k 1.249 · cl100k 1.869 · Gemma 3 1.079 · Mistral L4 1.223 · DeepSeek V4.1 0.939 · Qwen3 (2025) 1.003 · Qwen3.8 0.911 · Kimi K3 0.871 · GLM-5.3 0.946 · Llama 4 1.063</li><li><strong>Indonesian</strong>: o200k 1.249 · cl100k 1.551 · Gemma 3 1.154 · Mistral L4 1.266 · DeepSeek V4.1 1.349 · Qwen3 (2025) 1.542 · Qwen3.8 1.095 · Kimi K3 1.576 · GLM-5.3 1.539 · Llama 4 1.134</li><li><strong>German</strong>: o200k 1.311 · cl100k 1.586 · Gemma 3 1.328 · Mistral L4 1.243 · DeepSeek V4.1 1.515 · Qwen3 (2025) 1.559 · Qwen3.8 1.314 · Kimi K3 1.726 · GLM-5.3 1.450 · Llama 4 1.296</li><li><strong>Spanish</strong>: o200k <strong>1.318</strong> · cl100k <strong>1.544</strong> · Gemma 3 <strong>1.297</strong> · Mistral L4 <strong>1.256</strong> · DeepSeek V4.1 <strong>1.495</strong> · Qwen3 (2025) <strong>1.522</strong> · Qwen3.8 <strong>1.323</strong> · Kimi K3 <strong>1.689</strong> · GLM-5.3 <strong>1.442</strong> · Llama 4 <strong>1.298</strong></li><li><strong>Galician</strong>: o200k 1.335 · cl100k 1.562 · Gemma 3 1.354 · Mistral L4 1.288 · DeepSeek V4.1 1.524 · Qwen3 (2025) 1.543 · Qwen3.8 1.364 · Kimi K3 1.626 · GLM-5.3 1.486 · Llama 4 1.339</li><li><strong>French</strong>: o200k 1.370 · cl100k 1.608 · Gemma 3 1.412 · Mistral L4 1.297 · DeepSeek V4.1 1.547 · Qwen3 (2025) 1.582 · Qwen3.8 1.396 · Kimi K3 1.732 · GLM-5.3 1.512 · Llama 4 1.367</li><li><strong>Arabic</strong>: o200k 1.381 · cl100k 3.027 · Gemma 3 1.471 · Mistral L4 1.289 · DeepSeek V4.1 1.617 · Qwen3 (2025) 1.629 · Qwen3.8 1.309 · Kimi K3 2.052 · GLM-5.3 1.766 · Llama 4 1.589</li><li><strong>Russian</strong>: o200k 1.421 · cl100k 2.462 · Gemma 3 1.365 · Mistral L4 1.380 · DeepSeek V4.1 1.582 · Qwen3 (2025) 1.755 · Qwen3.8 1.363 · Kimi K3 2.046 · GLM-5.3 1.424 · Llama 4 1.228</li><li><strong>Turkish</strong>: o200k 1.431 · cl100k 1.921 · Gemma 3 1.370 · Mistral L4 1.323 · DeepSeek V4.1 2.041 · Qwen3 (2025) 1.624 · Qwen3.8 1.435 · Kimi K3 1.949 · GLM-5.3 1.645 · Llama 4 1.316</li><li><strong>Italian</strong>: o200k 1.469 · cl100k 1.641 · Gemma 3 1.376 · Mistral L4 1.247 · DeepSeek V4.1 1.544 · Qwen3 (2025) 1.626 · Qwen3.8 1.326 · Kimi K3 1.746 · GLM-5.3 1.530 · Llama 4 1.355</li><li><strong>Korean</strong>: o200k 1.472 · cl100k 2.367 · Gemma 3 1.374 · Mistral L4 1.384 · DeepSeek V4.1 1.643 · Qwen3 (2025) 1.630 · Qwen3.8 1.231 · Kimi K3 1.979 · GLM-5.3 1.919 · Llama 4 1.266</li><li><strong>Catalan</strong>: o200k 1.483 · cl100k 1.710 · Gemma 3 1.544 · Mistral L4 1.468 · DeepSeek V4.1 1.620 · Qwen3 (2025) 1.687 · Qwen3.8 1.551 · Kimi K3 1.715 · GLM-5.3 1.670 · Llama 4 1.522</li><li><strong>Hebrew</strong>: o200k 1.483 · cl100k 3.643 · Gemma 3 1.733 · Mistral L4 1.359 · DeepSeek V4.1 1.769 · Qwen3 (2025) 1.474 · Qwen3.8 1.826 · Kimi K3 2.255 · GLM-5.3 3.644 · Llama 4 1.737</li><li><strong>Swahili</strong>: o200k 1.486 · cl100k 1.954 · Gemma 3 1.639 · Mistral L4 1.610 · DeepSeek V4.1 1.940 · Qwen3 (2025) 1.936 · Qwen3.8 1.821 · Kimi K3 1.907 · GLM-5.3 1.932 · Llama 4 1.673</li><li><strong>Vietnamese</strong>: o200k 1.490 · cl100k 2.444 · Gemma 3 1.372 · Mistral L4 1.411 · DeepSeek V4.1 2.118 · Qwen3 (2025) 1.435 · Qwen3.8 1.308 · Kimi K3 2.792 · GLM-5.3 1.461 · Llama 4 1.328</li><li><strong>Hindi</strong>: o200k 1.574 · cl100k 4.759 · Gemma 3 1.311 · Mistral L4 1.594 · DeepSeek V4.1 2.795 · Qwen3 (2025) 4.416 · Qwen3.8 2.011 · Kimi K3 2.740 · GLM-5.3 4.315 · Llama 4 1.651</li><li><strong>Basque</strong>: o200k 1.604 · cl100k 1.881 · Gemma 3 1.678 · Mistral L4 1.569 · DeepSeek V4.1 1.737 · Qwen3 (2025) 1.866 · Qwen3.8 1.758 · Kimi K3 1.886 · GLM-5.3 1.840 · Llama 4 1.716</li><li><strong>Polish</strong>: o200k 1.639 · cl100k 1.914 · Gemma 3 1.507 · Mistral L4 1.781 · DeepSeek V4.1 1.684 · Qwen3 (2025) 1.765 · Qwen3.8 1.513 · Kimi K3 2.111 · GLM-5.3 1.691 · Llama 4 1.396</li><li><strong>Japanese</strong>: o200k 1.658 · cl100k 2.266 · Gemma 3 1.213 · Mistral L4 1.633 · DeepSeek V4.1 1.422 · Qwen3 (2025) 1.403 · Qwen3.8 1.163 · Kimi K3 1.643 · GLM-5.3 1.497 · Llama 4 1.306</li><li><strong>Bengali</strong>: o200k 1.697 · cl100k 5.799 · Gemma 3 1.211 · Mistral L4 1.539 · DeepSeek V4.1 2.017 · Qwen3 (2025) 5.026 · Qwen3.8 2.181 · Kimi K3 2.952 · GLM-5.3 4.713 · Llama 4 2.054</li><li><strong>Ukrainian</strong>: o200k 1.749 · cl100k 2.967 · Gemma 3 1.610 · Mistral L4 1.720 · DeepSeek V4.1 2.161 · Qwen3 (2025) 2.500 · Qwen3.8 1.739 · Kimi K3 2.159 · GLM-5.3 1.828 · Llama 4 1.539</li><li><strong>Tamil</strong>: o200k 1.980 · cl100k 7.644 · Gemma 3 1.469 · Mistral L4 1.706 · DeepSeek V4.1 3.070 · Qwen3 (2025) 6.112 · Qwen3.8 2.587 · Kimi K3 4.158 · GLM-5.3 7.644 · Llama 4 3.749</li></ul><p>What I take from this:</p><ul><li><strong>Spanish is in the temperate zone.</strong> In almost every tokenizer it sits between Portuguese and French, and below Italian, Catalan and Polish. If the Spanish surcharge hurts, think of whoever builds an app in Catalan (1.48 with o200k, 1.54 with Gemma) or in Basque (1.60 and 1.68).</li><li><strong>cl100k is a disaster outside the Latin alphabet</strong>, and it&#39;s the tokenizer of GPT-4 and of the ChatGPT half the world used in 2023 and 2024: Hebrew 3.64, Hindi 4.76, Bengali 5.80, Tamil 7.64. With o200k those same figures drop to 1.48, 1.57, 1.70 and 1.98. For a Tamil user, OpenAI&#39;s tokenizer change cut the tokens by almost four.</li><li><strong>Chinese tokenizers are cheaper in Chinese than in English.</strong> Kimi 0.871, Qwen3.8 0.911, DeepSeek 0.939, GLM 0.946: the same sentence costs fewer tokens in Chinese than in English. My reading is that it’s the mirror image of what happens to Spanish with Western tokenizers: a tokenizer corpus with a lot of Chinese. It also matters that Chinese uses 67% fewer characters than English to say the same thing, so the per-sentence comparison favors it from the start. Meanwhile, o200k gives 1.249 and cl100k 1.869 for Chinese.</li><li><strong>A “better” tokenizer isn’t better at everything.</strong> Gemma 3 is the best of the group for Hindi (1.31), Bengali (1.21) and Tamil (1.47), yet for Portuguese (1.26), French (1.41) or Dutch (1.38) it is beaten by Mistral Large 4, o200k and Llama 4. Mistral Large 4 is the best for Spanish, Portuguese, Dutch, German and Italian and one of the worst for Polish (1.78). There&#39;s no winner; there&#39;s a winner per language.</li><li><strong>GLM-5.3 gives 7.644 for Tamil, the same figure as </strong><strong>cl100k (207,796 tokens against 207,772), and 3.644 for Hebrew against 3.643.</strong> I don&#39;t have the training corpus of either; my interpretation, and it is an interpretation, is that both run out of learned tokens for those scripts and fall back to chopping almost byte by byte, which is why they coincide.</li><li><strong>Qwen3 to Qwen3.8 is one of the biggest improvements by a single lab in the table</strong> (OpenAI’s between cl100k and o200k is bigger in Tamil, Bengali and Hindi): Hindi from 4.42 to 2.01, Bengali from 5.03 to 2.18, Tamil from 6.11 to 2.59. If you use Qwen with Indic languages and haven&#39;t upgraded, you&#39;re paying twice what you need to.</li></ul><h4>The byte correction</h4><p>For Spanish I separated length from the tokenizer by dividing by the character ratio. For a 25-language table that doesn’t work: Chinese has 67% <em>fewer</em> characters than English to say the same thing, Japanese 57% fewer, Korean 50% fewer, and dividing by that would give factors of 3 and 4 that describe nothing real. The honest unit for comparing across scripts is the UTF-8 byte, which is what the tokenizer actually sees. This table is the token ratio divided by the byte ratio: how much worse the tokenizer compresses each byte of that language than each byte of English.</p><ul><li><strong>Spanish</strong>: o200k 1.088 · cl100k 1.275 · Gemma 3 1.071 · Mistral L4 1.038 · DeepSeek V4.1 1.235 · Qwen3.8 1.093 · Kimi K3 1.395 · GLM-5.3 1.191 · Llama 4 1.072</li><li><strong>Portuguese</strong>: o200k 1.097 · cl100k 1.324 · Gemma 3 1.126 · Mistral L4 1.035 · DeepSeek V4.1 1.274 · Qwen3.8 1.111 · Kimi K3 1.447 · GLM-5.3 1.257 · Llama 4 1.097</li><li><strong>French</strong>: o200k 1.103 · cl100k 1.295 · Gemma 3 1.137 · Mistral L4 1.044 · DeepSeek V4.1 1.246 · Qwen3.8 1.124 · Kimi K3 1.394 · GLM-5.3 1.218 · Llama 4 1.101</li><li><strong>German</strong>: o200k 1.107 · cl100k 1.340 · Gemma 3 1.122 · Mistral L4 1.050 · DeepSeek V4.1 1.280 · Qwen3.8 1.110 · Kimi K3 1.458 · GLM-5.3 1.225 · Llama 4 1.095</li><li><strong>Italian</strong>: o200k 1.234 · cl100k 1.378 · Gemma 3 1.156 · Mistral L4 1.047 · DeepSeek V4.1 1.297 · Qwen3.8 1.114 · Kimi K3 1.466 · GLM-5.3 1.285 · Llama 4 1.138</li><li><strong>Catalan</strong>: o200k 1.316 · cl100k 1.518 · Gemma 3 1.370 · Mistral L4 1.303 · DeepSeek V4.1 1.438 · Qwen3.8 1.376 · Kimi K3 1.522 · GLM-5.3 1.482 · Llama 4 1.351</li><li><strong>Polish</strong>: o200k 1.460 · cl100k 1.705 · Gemma 3 1.342 · Mistral L4 1.587 · DeepSeek V4.1 1.501 · Qwen3.8 1.348 · Kimi K3 1.881 · GLM-5.3 1.507 · Llama 4 1.244</li><li><strong>Basque</strong>: o200k 1.510 · cl100k 1.772 · Gemma 3 1.580 · Mistral L4 1.477 · DeepSeek V4.1 1.636 · Qwen3.8 1.656 · Kimi K3 1.776 · GLM-5.3 1.732 · Llama 4 1.615</li><li><strong>Russian</strong>: o200k 0.721 · cl100k 1.249 · Gemma 3 0.693 · Mistral L4 0.700 · DeepSeek V4.1 0.803 · Qwen3.8 0.692 · Kimi K3 1.038 · GLM-5.3 0.723 · Llama 4 0.623</li><li><strong>Ukrainian</strong>: o200k 0.939 · cl100k 1.594 · Gemma 3 0.865 · Mistral L4 0.924 · DeepSeek V4.1 1.161 · Qwen3.8 0.934 · Kimi K3 1.160 · GLM-5.3 0.982 · Llama 4 0.826</li><li><strong>Arabic</strong>: o200k 0.864 · cl100k 1.893 · Gemma 3 0.920 · Mistral L4 0.806 · DeepSeek V4.1 1.011 · Qwen3.8 0.818 · Kimi K3 1.283 · GLM-5.3 1.104 · Llama 4 0.993</li><li><strong>Hebrew</strong>: o200k 1.070 · cl100k 2.629 · Gemma 3 1.251 · Mistral L4 0.980 · DeepSeek V4.1 1.277 · Qwen3.8 1.317 · Kimi K3 1.627 · GLM-5.3 2.629 · Llama 4 1.253</li><li><strong>Hindi</strong>: o200k 0.617 · cl100k 1.865 · Gemma 3 0.514 · Mistral L4 0.625 · DeepSeek V4.1 1.095 · Qwen3.8 0.788 · Kimi K3 1.074 · GLM-5.3 1.691 · Llama 4 0.647</li><li><strong>Bengali</strong>: o200k 0.650 · cl100k 2.222 · Gemma 3 0.464 · Mistral L4 0.590 · DeepSeek V4.1 0.773 · Qwen3.8 0.836 · Kimi K3 1.131 · GLM-5.3 1.806 · Llama 4 0.787</li><li><strong>Tamil</strong>: o200k 0.620 · cl100k 2.395 · Gemma 3 0.460 · Mistral L4 0.535 · DeepSeek V4.1 0.962 · Qwen3.8 0.810 · Kimi K3 1.303 · GLM-5.3 2.395 · Llama 4 1.175</li><li><strong>Chinese (simpl.)</strong>: o200k 1.365 · cl100k 2.044 · Gemma 3 1.179 · Mistral L4 1.337 · DeepSeek V4.1 1.027 · Qwen3.8 0.996 · Kimi K3 0.953 · GLM-5.3 1.035 · Llama 4 1.163</li><li><strong>Japanese</strong>: o200k 1.311 · cl100k 1.791 · Gemma 3 0.959 · Mistral L4 1.291 · DeepSeek V4.1 1.124 · Qwen3.8 0.919 · Kimi K3 1.299 · GLM-5.3 1.183 · Llama 4 1.032</li><li><strong>Korean</strong>: o200k 1.233 · cl100k 1.981 · Gemma 3 1.151 · Mistral L4 1.159 · DeepSeek V4.1 1.375 · Qwen3.8 1.031 · Kimi K3 1.656 · GLM-5.3 1.606 · Llama 4 1.060</li></ul><p>Read this way, things change. A value below 1 means the tokenizer compresses that language’s bytes <em>better</em> than English’s, and it happens in Russian, Ukrainian, Arabic, Hindi, Bengali and Tamil with o200k, Gemma 3, Mistral Large 4 and Qwen3.8: they&#39;ve learned multi-letter tokens for those scripts. Hindi pays 1.57 with o200k not because the tokenizer treats it worse per byte (0.62, it treats it much better), but because Hindi in UTF-8 takes 2.55 times the bytes of English. There the tax isn&#39;t the tokenizer&#39;s; it&#39;s the encoding&#39;s. And Spanish, with all the renewed tokenizers, sits between 1.04 and 1.09 per byte: there&#39;s little left to scrape. Whoever still pays a high pure penalty in Spanish is whoever hasn&#39;t renewed: cl100k (1.28), DeepSeek (1.24), GLM (1.19) and Kimi (1.40).</p><h4>Claude and Gemini: what I couldn’t measure</h4><p>I don’t want the absence of Claude and Gemini from the tables to be read as meaning they have no surcharge. They have one, surely, because every tokenizer trained on more English than Spanish does; what I don’t know is how much.</p><p><strong>Gemini.</strong> Google doesn’t publish the API tokenizer, but it has said that Gemma 3 uses “the same tokenizer as Gemini 2.0”. Gemma 3 and Gemma 4 give me identical counts in English and Spanish (35,167 tokens in Spanish in all four models I tried, Gemma 3 4B and 27B, Gemma 4 12B and 31B, which are three different files: the two Gemma 3 ones share a hash), so it’s reasonable to think the family hasn’t changed tokenizer and that Gemini sits near 1.30 for Spanish. It’s the best approximation I have and I mark it as such in the dollar table; if Gemini 4 introduced a new tokenizer, I don’t know.</p><p><strong>Claude.</strong> Anthropic doesn’t publish the tokenizer and I don’t know of any open model that shares it, so I have no possible approximation without the API. The only thing its documentation says about it is that the tokenizer changed recently: “Claude 4.7 and later models and Claude Mythos Preview use a newer tokenizer. The same input text produces approximately 30 percent more tokens than on earlier models. The exact increase depends on the content and workload shape. Recount prompts against the model you plan to use rather than reusing counts measured against earlier models”. It says nothing about languages, and I won’t either. I’ll keep the advice, which is good and applies to everyone: count against the model you’re going to use, not the one from six months ago.</p><p>If you have a key for either, the script at the end accepts any counting function; swap it for a call to their counting API and you’ll have the row I’m missing. If you do, tell me.</p><h4>What I would do</h4><p>The practical part, in order of how much money it moves.</p><p><strong>1. Measure with your own text before choosing a model.</strong> FLORES is translated text from Wikinews, Wikibooks and Wikivoyage. Your prompts have JSON, field names in English, code, a system prompt that may be half the context. Take a hundred real conversations, run them through each candidate’s tokenizer (tiktoken for OpenAI, Hugging Face tokenizers for almost all the open ones, mistral-common for Mistral, the counting API for Claude and Gemini) and multiply by the price. It&#39;s an afternoon&#39;s work and it&#39;s the only figure that holds for your case. This article&#39;s script does exactly that with FLORES; swap the corpus.</p><p><strong>2. Compare effective prices, not list prices.</strong> When two models cost about the same on the pricing page, the tokenizer decides. GLM-5.3 at 1.40 input looks quite a bit cheaper than qwen3.8-max at 2.00; in Spanish it&#39;s 2.02 against 2.65, and the gap narrows. If one of the candidates has an unrenewed 2024 tokenizer (cl100k, Llama 3, Qwen3, Kimi), add 50% before comparing.</p><p><strong>3. The surcharge isn’t only money: it’s also context window, tokens-per-minute limit and latency.</strong> A Spanish document takes 1.3 or 1.5 times more tokens, so it fills the window sooner, uses up the per-minute quota sooner and, since output tokens are generated one at a time, the same answer takes longer to come out. I haven’t measured this in seconds; I deduce it from how autoregressive models work, and I say so so you keep it in mind when sizing.</p><p><strong>4. The system prompt: what I know and what I don’t.</strong> What I know from arithmetic: the part of your request that’s in English doesn’t pay the surcharge. If your system prompt is 2,000 fixed tokens in Spanish and you switch it to English, with o200k you save on the order of 480 tokens per call (2,000 × 0.318 / 1.318), and that saving multiplies by every call of the day. What I don&#39;t know, and won&#39;t claim because I haven&#39;t measured it: whether the model answers as well in Spanish with English instructions. I have no data in either direction. If you do it, run the A/B test with your task and your users; if you can&#39;t, don&#39;t take it as given because a thread says so.</p><p><strong>5. If your users write in a language other than yours, look at their row, not yours.</strong> The 25-language table is there for that. A product for Brazil, Germany or the Netherlands has the Spanish surcharge or less. One for India, Israel or Poland has surcharges that swing from 1.3 to 4.7 depending on the tokenizer, and there the provider choice is the most important cost decision you’ll make.</p><p><strong>6. When the model changes, count again.</strong> The three big jumps in the table (OpenAI, Meta, Qwen) cut the Spanish surcharge by 20 points from one generation to the next. Anthropic’s raised tokens by around 30%, depending on content. Counts expire with the tokenizer, not with the calendar.</p><h4>How I measured it</h4><p>Everything is reproducible and published alongside this article.</p><ul><li><strong>Corpus</strong>: FLORES-200, <em>devtest</em>, 1,012 sentences per language, downloaded from Meta’s public link (flores200_dataset.tar.gz). For the Spanish-English comparison I also used the <em>dev</em> set (997 sentences) as a check; the ratios change by at most 0.012 between the two (cl100k: 1.544 on <em>devtest</em>, 1.548 on <em>dev</em>; the published script doesn&#39;t repeat this check, it only measures the <em>devtest</em>). I checked that the 1,012 lines of each language are aligned (same sentence on the same line) at five points in the file, and that Unicode NFC normalization doesn&#39;t change the character count.</li><li><strong>Tokenizers</strong>: only the tokenizer files, never the weights, downloaded from Hugging Face at a pinned revision (the commit hash is in the results.json table). tiktoken 0.14.0 for o200k_base, cl100k_base and o200k_harmony; the tokenizers library for the tokenizer.json files; mistral-common for Mistral&#39;s tekken.json files; Moonshot&#39;s official tokenization_kimi.py via AutoTokenizer for Kimi. In every case, add_special_tokens=False: I count the text, not the start and end markers.</li><li><strong>Mirrors</strong>: the Llama 3.3, Llama 4 Scout and Gemma 3 tokenizers come from unsloth repositories, ungated copies that I assume are identical to Meta&#39;s and Google&#39;s official files (the official ones return 401 without accepting the license, so I couldn&#39;t check hash against hash). For Gemma 3 I checked that the tokenizer.json of the 4B copy and the 27B one have the same SHA-256. Gemma 4 (12B and 31B) does come from the official google/ repositories, and gives the same counts as Gemma 3 with different files.</li><li><strong>Second path</strong>: four counts in the Spanish-English table were computed by two different paths and matched to the token: o200k_base with tiktoken and with the tokenizer.json of Xenova/gpt-4o loaded into tokenizers (26,873 and 35,415 by both), Kimi with its official class and with the tiktoken.model file, Mistral Large 4 with tekken.json and with tokenizer.json, and gpt-oss with its tokenizer.json against o200k_base. The rest was counted once. Where two files of the same family gave identical counts, I checked with the file hash and say so in the table.</li><li><strong>Intervals</strong>: non-parametric <em>bootstrap</em> over the 1,012 sentences, 10,000 resamples, seed 12345, 2.5 and 97.5 percentiles of the ratio of totals.</li><li><strong>The other languages</strong>: same procedure with 25 FLORES-200 codes and ten tokenizers; each tokenizer gives ratio 1.000 for English against itself, which is the check that the script doesn’t swallow lines.</li><li><strong>Prices</strong>: read from each provider’s official page on October 31, 2026 (OpenAI, DeepSeek, Z.ai, Moonshot, Alibaba Cloud Model Studio international, Google AI). DeepSeek has peak and off-peak rates; I use peak. I don’t use Mistral’s because of the conflict between two official pages I’ve already described.</li></ul><p>The files:</p><ul><li><a href="https://blog.danielalfocea.com/images/posts/impuesto-idioma-tokens/reproduce.py">reproduce.py</a>: a single self-contained script. It downloads FLORES-200, fetches each tokenizer at its pinned revision, counts Spanish against English with the 16 tokenizers (with the <em>bootstrap</em> and the count of frequent words that fit in one token) and the 25 languages with ten, and writes the two JSON files.</li><li><a href="https://blog.danielalfocea.com/images/posts/impuesto-idioma-tokens/results.json">results.json</a> and <a href="https://blog.danielalfocea.com/images/posts/impuesto-idioma-tokens/langs.json">langs.json</a>: the raw numbers every table in this article comes from, with the repository and revision of each tokenizer.</li></ul><p>You need Python 3 with numpy, tiktoken, tokenizers, transformers, huggingface_hub and mistral-common. The script downloads the corpus and the tokenizer files the first time.</p><h4>Conclusion</h4><p>Spanish pays between 26% and 69% more than English for the same sentence, depending on the tokenizer, and that surcharge splits in two: 19 points that belong to the language and can’t be removed, and between 7 and 50 that belong to the tokenizer and that some labs have already almost entirely removed. The difference between paying 1.26 and paying 1.69 isn’t on the pricing page; it’s in a tokenizer.json file that almost nobody opens.</p><p>What I take away from counting all this is that the question “how much does this model cost?” has no answer without the question “in what language?”. And that the answer changes faster than it seems: three labs cut the Spanish surcharge from 50% to 30% between two measured versions, and three others have run the same file for several generations. If your application speaks Spanish, Hindi, Polish or Catalan, count your tokens against the model you’re going to use, with your own text, before signing anything. It’s an afternoon’s work, and it’s the most profitable afternoon of the project.</p><p>Originally published on my blog: <a href="https://blog.danielalfocea.com/en/impuesto-idioma-tokens/">https://blog.danielalfocea.com/en/impuesto-idioma-tokens/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=096b0bb506dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The October 29 Binance theft: 50 signatures, one lucky nonce and a hot wallet that stopped being…]]></title>
            <link>https://cr0hn.medium.com/on-october-29-2026-at-20-20-59-utc-the-binance-hot-wallet-known-as-binance-14-stopped-being-an-becd5588e542?source=rss-e88f464b9d9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/becd5588e542</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Daniel Alfocea]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 09:10:54 GMT</pubDate>
            <atom:updated>2026-11-05T10:22:32.140Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NHtXTOXAuyQgTBTi.png" /></figure><h3>The October 29 Binance theft: 50 signatures, one lucky nonce and a hot wallet that stopped being theirs</h3><h4>On-chain analysis of the Binance 14 hot wallet drain with EIP-7702</h4><p>On October 29, 2026, at 20:20:59 UTC, the Binance hot wallet known as Binance 14 stopped being an ordinary Ethereum account and started running someone else’s code. Three minutes and twenty-four seconds later, that code pulled 167,464 ETH and 1.615 billion USDT out of the account in a single transaction. The account kept receiving deposits for almost four hours, and every time something came in, it was swept again. The revocation was signed at 00:10:35 on the 30th.</p><p>I spent the following day reconstructing what happened with the chain as my only source: Blockscout, a public RPC node and a disassembler. Throughout this piece I keep what I verified apart from what third parties say, because in the first 24 hours of an incident like this everything circulates, and some of it is false.</p><h4>What I verified and what I didn’t</h4><p>Everything in this article that carries a hash or an address I checked against Ethereum mainnet between 12:00 and 18:00 UTC on October 30, using three public tools and no API key:</p><ul><li>The <a href="https://docs.blockscout.com/devs/apis/rest">Blockscout</a> API v2 (https://eth.blockscout.com/api/v2/) for transactions, authorization lists and transfers.</li><li>The public RPC https://ethereum-rpc.publicnode.com for eth_getCode, eth_call, eth_getBlockByNumber and eth_getLogs. It is not an archive node, so it can&#39;t tell you an account&#39;s state at an old block.</li><li><a href="https://github.com/crytic/pyevmasm">pyevmasm</a> to disassemble the contract. With Foundry, cast disassemble does the same.</li></ul><p>What I couldn’t verify is attributed to whoever says it. The total figures for the theft (the press, such as <a href="https://cointelegraph.com/news/binance-hack-may-involve-private-key-misuse-not-theft-blockaid-ceo">Cointelegraph</a> and <a href="https://decrypt.co/382203/binance-finds-additional-points-of-breach-in-6-3b-hack">Decrypt</a>, reports about 6.3 billion dollars; according to <a href="https://decrypt.co/382224/trm-and-chainalysis-tie-6-4b-binance-hack-to-north-koreas-tradertraitor">Decrypt</a>, Chainalysis puts it at 6.4 billion and TRM at 6.36, and Binance says it has set aside 6.34 billion to cover losses, <a href="https://decrypt.co/382237/binance-sets-aside-6-34b-to-cover-hack-losses-ceo-says-your-assets-are-safe">per Decrypt</a>), what happened on the other nine chains that are mentioned, the way in (Binance says the attacker may have used a compromised DevOps engineer’s laptop, per <a href="https://cointelegraph.com/news/binance-hack-may-involve-private-key-misuse-not-theft-blockaid-ceo">Cointelegraph</a>, and later that it found “additional points of breach”, per <a href="https://decrypt.co/382203/binance-finds-additional-points-of-breach-in-6-3b-hack">Decrypt</a>) and the attribution to TraderTraitor, a North Korean group usually associated with the Lazarus umbrella (made by <a href="https://www.trmlabs.com/resources/blog/north-korea-steals-usd-6-36-billion-from-binance-in-the-largest-hack-in-history">TRM Labs</a> and <a href="https://www.chainalysis.com/blog/binance-exploit-latest-findings-and-response/">Chainalysis</a>). None of that is on the Ethereum chain, and I only looked at the Ethereum chain.</p><p>Dollar prices are approximate, as of October 30.</p><h4>The addresses</h4><ul><li><strong>Victim: Binance 14</strong>: <a href="https://etherscan.io/address/0x28C6c06298d514Db089934071355E5743bf21d60">0x28C6c06298d514Db089934071355E5743bf21d60</a></li><li><strong>Operator</strong>: <a href="https://etherscan.io/address/0x7C8601d4645b93cea45F71e118A729332e6B5CA0">0x7C8601d4645b93cea45F71e118A729332e6B5CA0</a></li><li><strong>Sweeper (delegated contract)</strong>: <a href="https://etherscan.io/address/0x63e842B054Bd624a465454D533C33F573e9c6fAe">0x63e842B054Bd624a465454D533C33F573e9c6fAe</a></li><li><strong>Recipient 1</strong>: <a href="https://etherscan.io/address/0x5227f603C1eE34CE3C06eFe6477003BDfCCB2f8c">0x5227f603C1eE34CE3C06eFe6477003BDfCCB2f8c</a></li><li><strong>Recipient 2</strong>: <a href="https://etherscan.io/address/0xA97bF7836F8A08F9Ed91D41453D371493FAE8d10">0xA97bF7836F8A08F9Ed91D41453D371493FAE8d10</a></li></ul><p>Labels such as “Binance 14” come from explorer services, not from the account itself. I use them because they are what you will see on Etherscan, but remember that nobody has signed them.</p><h4>EIP-7702 in five minutes</h4><p>Until May 2025, Ethereum had two kinds of account that never mixed. Externally owned accounts (EOAs) have a private key and no code; contracts have code and no key. If your key signed something, that something was a transaction, and the transaction did one thing and was over. Off-chain signatures already existed, such as EIP-712 and permit (ERC-2612), authorizing later operations, but they covered one token or one contract, not the whole account.</p><p><a href="https://eips.ethereum.org/EIPS/eip-7702">EIP-7702</a>, activated on mainnet with the <a href="https://ethereum.org/en/roadmap/pectra/">Pectra</a> fork on May 7, 2025, breaks that separation on purpose, and what is new is the persistent delegation of the entire account’s code. An EOA can sign an authorization that says: when someone calls my address, run contract X’s code as if it were mine. The mechanism has four pieces:</p><ol><li>A new transaction type, 0x04, with an extra field: authorization_list.</li><li>Each authorization is a tuple [chain_id, address, nonce, y_parity, r, s]. The signature belongs to the delegating EOA, not to whoever sends the transaction. The account paying for gas and the account delegating can be two different ones. Here they were.</li><li>When processing it, the node writes a delegation designator into the EOA’s account: the bytes 0xef0100 followed by the contract&#39;s address. From then on, any call to the EOA runs that code with the EOA&#39;s address (address(this)), balance and storage. Careful: msg.sender is whoever calls, not the EOA. That is why the sweeper compares CALLER with the operator, as the bytecode section shows.</li><li>The delegation does not expire. It stays until the EOA signs another authorization pointing to a different address, or to the zero address to revoke it.</li></ol><p>Point 4 is what turns a signature into a permanent door. A transaction signed by mistake runs once. A 7702 authorization signed by mistake gives whoever controls the delegated contract a key to the account that no longer depends on using the private key again. While the delegation stays in place, the sweep repeats with ordinary transactions sent by the operator.</p><p>The feature was designed for good things: letting a user wallet pay its own gas in tokens, batch several actions into one, or set a spending limit, without migrating to a smart account. Here it was used for the opposite.</p><h4>The type 4 transaction: 50 signatures, one valid</h4><p>The delegation landed in block 26,300,753, at 20:20:59 UTC, in transaction <a href="https://etherscan.io/tx/0xad99264d5532ae0dd04b2004eebda05f25657e70dacb764f7ac8d4ccd051298b">0xad99264d5532ae0dd04b2004eebda05f25657e70dacb764f7ac8d4ccd051298b</a>. It was sent by the operator 0x7C86…5CA0, who paid the gas, and it carries <strong>50 authorizations</strong>. All 50 delegate to the same sweeper 0x63e842…6fAe, and all 50 are signed by the same account: Binance 14.</p><p>The structure, field by field, is this (an EOA delegating to a contract has this shape):</p><pre>Transaction type 0x04 (EIP-7702)<br>├── chain_id, nonce, max_priority_fee, max_fee, gas_limit<br>├── destination = 0x28C6…1d60   (Binance 14 itself)<br>├── value = 0, data = 0x<br>└── authorization_list = [<br>      { chain_id: 1, address: 0x63e842…6fAe, nonce: 18914824, y_parity, r, s },<br>      { chain_id: 1, address: 0x63e842…6fAe, nonce: 18914823, ... },<br>      ...  consecutive nonces, in descending order ...<br>      { chain_id: 1, address: 0x63e842…6fAe, nonce: 18914809, ... },  (position 16, the valid one)<br>      ...<br>      { chain_id: 1, address: 0x63e842…6fAe, nonce: 18914775, ... }<br>    ]</pre><p>The 50 nonces run in sequence and the list is descending, from 18,914,824 to 18,914,775. When recovering the signer of each signature, Blockscout returns the authority field, and in all 50 it is the same: 0x28C6…1d60. That settles two things that had been published as rumor and that I can now treat as checked: there were 50 authorizations, and the nonces were these.</p><p>The trick of including 50 lies in how the protocol validates an authorization. The nonce in each tuple has to match the account&#39;s current nonce <strong>exactly</strong> at the moment it is processed. If it doesn&#39;t match, that authorization is dropped without aborting the transaction: the rest keep being tried. The attacker couldn&#39;t know for sure what nonce Binance 14 would be at when the transaction was mined, because it is a hot wallet with constant traffic and the nonce keeps rising. So they signed a window of 50 nonces that included the expected value (34 below it and 15 above) and sent all 50 together. Whichever one hit would go through.</p><p>The one with nonce <strong>18,914,809</strong> hit, in position 16 of the list. The order matters: after an authorization is applied, the account’s nonce goes up by one, and in ascending order the following ones would have matched too. The transaction detail shows the per-authorization status: 18,914,809 reads ok and the other 49 read invalid_nonce. One is enough: the account was delegated.</p><p>The gas cost confirms it. The transaction used 1,258,562 gas. The intrinsic cost of 50 authorizations is 21,000 + 50 × 25,000 = 1,271,000, and each authorization whose account already exists refunds 12,500. That is 1,271,000 − 12,500 = 1,258,500, almost exactly what was observed (the rest, 62 gas, is the execution of receive). But the cost of the 50 tuples is paid whether they are valid or not, so the gas shows 50 tuples and exactly one refund, not why the other 49 failed. They were not repeated nonces: all 50 are distinct and 49 did not match the account&#39;s current nonce. The list and its status (invalid_nonce) say that, not the gas.</p><p>That all 50 signatures come from Binance 14’s key is the hard fact. What that fact implies is not. The chain can’t tell a signature made by an attacker who controls the key from one made by Binance itself; it only sees that the signature is valid. That this was a theft comes from Binance, not from the chain. If it was, 50 consecutive signatures with sequential nonces point to someone having access to the key or to the signing flow that uses it, not to a flaw in the contract or in EIP-7702. The protocol did exactly what it defines: it executed a delegation signed by its owner.</p><p>The dress rehearsal was in plain sight hours earlier. At 13:51:35 and 13:51:59 the operator sent two type 4 transactions on two test accounts: 0x16b5acc3… with 2 authorizations (nonces 1 and 0; only nonce 0 was valid) and 0xec5af21d… with 3 (nonces 2, 1 and 0; only 0 was valid). Both accounts delegate to an earlier contract, 0x19beE294…. It swept them at 14:19:59 and 14:24:11. On the third account (0x43AE…04BD) there were two type 4 transactions, at 16:20:47 and 16:25:59, each with two authorizations (nonces 0 and 1) pointing at the same sweeper; in each only one was valid. The operator then called sweep at 16:30:11 and withdrawETH at 16:47:23. The 14:19 and 14:24 sweeps use sweep before the 15:59 contract was deployed, so there was an earlier contract, deployed at 02:28 on the 29th. The final sweeper was deployed at 15:59, in transaction <a href="https://etherscan.io/tx/0x97408e7562eb2b28efcd24ba01609607b5749bc89448d007fa8b50ecf290329c">0x97408e75…</a>. The operator&#39;s gas came from the 0.1 ETH Tornado Cash pool (0x12D66f87…, labeled TornadoCash_Eth_01), in three withdrawals of 0.098 ETH on the 28th and 29th.</p><h4>The sweeper, from the bytecode</h4><p>Contract 0x63e842…6fAe has 1,674 bytes of runtime code. I pulled it with eth_getCode and disassembled it with pyevmasm. You don&#39;t need to write a disassembler: the library exists and solves this in ten lines.</p><pre>from pyevmasm import disassemble_all<br>code = bytes.fromhex(open(&quot;sweeper.hex&quot;).read()[2:])<br>for ins in disassemble_all(code):<br>    print(f&quot;{ins.pc:04x}: {ins}&quot;)</pre><p>A warning: the current pyevmasm does not know PUSH0 (0x5f, since Shanghai). Its newest fork is istanbul (the default; fork=&quot;shanghai&quot; raises KeyError), so it prints INVALID where there is a PUSH0. In the listings in this article I read it as PUSH0: the bytes 5f 80 fd at 0x15-0x17 are PUSH0 DUP1 REVERT.</p><p>The entry dispatcher compares the first four bytes of the calldata (the selector) against five functions:</p><pre>001c: CALLDATALOAD<br>001d: PUSH1 0xe0<br>001f: SHR                      ; selector = calldata[0:4]<br>0021: PUSH4 0x01e33667  EQ ... ; withdrawToken(address,address,uint256)<br>002c: PUSH4 0x043ff9d2  EQ ... ; callExecute(address,address,uint256,bytes)<br>0037: PUSH4 0x4782f779  EQ ... ; withdrawETH(address,uint256)<br>0042: PUSH4 0x8a179be4  EQ ... ; sweep(address,address[])<br>004c: PUSH4 0x97dc97cb  SUB... ; authorizedCaller()</pre><p>All five selectors resolve on <a href="https://www.4byte.directory/">4byte</a> and <a href="https://openchain.xyz/signatures">openchain</a> without ambiguity. One of them, 0x043ff9d2, is missing from 4byte but present on openchain: callExecute(address,address,uint256,bytes).</p><p>Access control is the first thing every function with side effects does. The operator check appears identically on entry to sweep, withdrawETH, withdrawToken and callExecute. The CALLVALUE check (revert if you send ETH) is not in all four: callExecute forwards CALLVALUE, so it does not revert if you send it ETH.</p><pre>0088: CALLVALUE  PUSH2 0x83  JUMPI     ; if you send ETH with the call, revert (callExecute has no such check)<br>...<br>00e2: PUSH20 0x7c8601d4645b93cea45f71e118a729332e6b5ca0<br>00f7: CALLER                           ; msg.sender<br>00f8: SUB                              ; authorizedCaller - msg.sender<br>00f9: PUSH2 0x2e7  JUMPI               ; if non-zero, jump to revert</pre><p>The operator’s address 0x7C86…5CA0 is embedded in the bytecode as a constant. The only account that can call any function with side effects is that one. It is the classic onlyAuthorized, but with the address burned into the code instead of sitting in a storage variable, so it can&#39;t be changed. The authorizedCaller() view (selector 0x97dc97cb) returns that same constant from PUSH20 … MSTORE RETURN, without going through access control.</p><p>There is a receive (it accepts ETH with no data: the STOP at 0x0019 after checking that the calldata is empty) and no fallback with logic: any selector outside the five, or a call with calldata, ends in PUSH0 DUP1 REVERT (0x15-0x17). The INVALID at 0x654 is the fe that closes the code; what follows right after (starting at 0xa2) is the compiler&#39;s CBOR metadata, which is not code that gets executed. There is no SELFDESTRUCT, no DELEGATECALL, no storage: everything is constants and calldata. It is a stateless, disposable contract.</p><p>sweep(address to, address[] tokens) is the core. It walks the list of tokens:</p><ul><li>If the token is the zero address, it treats the entry as ETH: it reads SELFBALANCE, and if the balance is above 1 ether (0xde0b6b3a7640000) it sends the balance minus 1 ether with a CALL. It always leaves 1 ETH in the account; the bytecode does not say why.</li><li>If it is a regular token, it makes a staticcall to balanceOf(address(this)) (selector 0x70a08231), and if the balance is greater than zero it calls transfer(to, balance) (selector 0xa9059cbb).</li><li>If a transfer fails, it does not abort the sweep: it emits an event with a code (I saw LOG2 with the same topic 0x394e1e4b… on the failure branches) and moves on to the next token. That is why a single sweep can move 65 assets even if three of them revert.</li></ul><p>The sweep’s tolerance for failures is what makes it dangerous: you hand it a long list of tokens, it sweeps every one it can and doesn’t get stuck on the ones it can’t. I reconstructed it as pseudo-Solidity to read at a glance:</p><pre>function sweep(address payable to, address[] calldata tokens) external onlyAuthorized {<br>    for (uint256 i = 0; i &lt; tokens.length; i++) {<br>        address token = tokens[i];<br>        if (token == address(0)) {<br>            uint256 bal = address(this).balance;<br>            if (bal &gt; 1 ether) { (bool ok,) = to.call{value: bal - 1 ether}(&quot;&quot;); /* if it fails, emit event and continue */ }<br>        } else {<br>            (bool s, bytes memory r) = token.staticcall(abi.encodeCall(IERC20.balanceOf, (address(this))));<br>            if (!s || r.length &lt; 32) continue;                 // odd token: skip it<br>            uint256 bal = abi.decode(r, (uint256));<br>            if (bal &gt; 0) token.call(abi.encodeCall(IERC20.transfer, (to, bal)));  // if it fails, continue<br>        }<br>    }<br>}</pre><p>callExecute is the other mechanism, and the one that explains the two USDC movements. It checks that the target has code (EXTCODESIZE; if it is zero it reverts with NoCodeAtExecutor) and forwards an execute(address,uint256,bytes) call to it (selector 0xb61d27f6). It is the execution pattern of ERC-4337-style smart accounts. Binance 14, already carrying the sweeper&#39;s code, used it to order one of its own smart accounts to release the USDC. More on that shortly.</p><p>A note on the contract’s “source”. Blockscout shows a verified Target.sol, but the file itself warns in its header that it is an AI reconstruction from the bytecode made at 00:30 UTC on October 30, not the original code. The runtime compiles byte for byte identically, so the logic is reliable; the contract and parameter names are guesses. What I describe above comes from the disassembly, not from that source.</p><h4>How the deposits were drained</h4><p>Binance 14 is a deposit hot wallet: it receives customer deposits around the clock. The attacker didn’t empty it once; they built a sweep loop. Here are the transactions sent by Binance 14 itself (the ones carrying its nonce; the sweeps are sent by the operator) in ten-minute windows:</p><pre>transactions sent by Binance 14, per ten-minute window<br>20:20  38 sends     (delegation starts)<br>20:30  11<br>20:40   1<br>...<br>22:50  18<br>23:00  28<br>00:00   1<br>00:10   1           (revocation at 00:10:35)<br>00:20 157           (compatible with a return to normal operation)</pre><p>The table does not count sweeps. The loop shows in the ones the operator launched: between the first big sweep and the revocation, it launched more sweep calls as money came in: at 21:04, 21:44, 22:39 and 23:56, plus five empty sweeps from 23:36 on, when nothing was left to take (23,100 gas each, the cost of walking a list and transferring nothing).</p><p>The clearest case of the loop is the 200 million USDT transfer. Between the 21:04 sweep and the 21:44 one, 200.4 M USDT arrived at Binance 14 in 95 transfers (per USDT Transfer logs), 200 M of it in a single one from 0x22132139bf7f3921b1cadeab931f4fbf7bf2bc9e. At 21:44 the sweep <a href="https://etherscan.io/tx/0x55ba4dabc41b468e580751373ad31acdee6f5ba398682df2c93e5a8340870556">0x55ba4dab…</a> took it. In other words: money that reached Binance&#39;s already compromised account and went out the back door minutes after it came in.</p><h4>The flow of funds</h4><p>Aggregating the transfers from the seven sweeps that carried loot (at approximate October 30 prices, rounded):</p><ul><li><strong>USDT</strong>: 1,819 M · ~$1,800 M</li><li><strong>USDC</strong>: 823 M · ~$820 M</li><li><strong>ETH (sweeps)</strong>: 172,624 ETH · ~$380 M</li><li><strong>WBETH</strong>: 29,934 · ~$74 M</li><li><strong>RLUSD</strong>: 62.6 M · ~$63 M</li><li><strong>XAUT (tokenized gold)</strong>: 11,374 · ~$44 M</li><li><strong>UNI</strong>: 6.2 M · ~$43 M</li><li><strong>ENA, PEPE, USD1, LINK, AAVE…</strong>: various · tens of $M each</li></ul><p>What I could add up on Ethereum alone, at approximate October 30 prices, exceeds 3.2 billion dollars, and that leaves out a good part of the 122 minor tokens in the last sweep. I neither reach nor validate the 6,300–6,400 M published as the multi-chain total: that would include the other nine networks, which I haven’t looked at.</p><p>The split by destination:</p><ul><li><strong>Recipient 1</strong> (0x5227f6…2f8c): the bulk. USDT, USDC, the 167,464 ETH from the first sweep, and the 823 M USDC that went out through callExecute.</li><li><strong>Recipient 2</strong> (0xA97bF7…8d10): the 122 minor tokens and the last 2,962 ETH.</li></ul><p>Both recipients are EOAs with no code (eth_getCode returns 0x for both). From there the money didn&#39;t sit still:</p><ul><li><strong>The ETH was consolidated.</strong> Recipient 1 sent 195,460 ETH to 0x8532FA14… at 20:38, 2,000 ETH to the same address at 01:14, and 17,260 ETH to 0x03b0eE5d…. Recipient 2 sent 3,000 ETH to 0xc2096a12… and 7,647 ETH to 0x54401f80…. Those addresses accumulate the ETH and still hold balances today: 197,460, 40,600 and 17,260 ETH. It has not moved to any mixer or bridge from there, at least as far as I looked.</li><li><strong>Binance 16’s 28,005 ETH enter the picture.</strong> At 20:24:47, four minutes after the first sweep, the Binance 16 hot wallet (0xDFd5293D…) sent 28,005.6 ETH to recipient 1 in a normal type 2 transaction, signed with its own key, nonce 15,703,491. It is not a 7702 delegation, it is an ordinary transfer. A second Binance hot wallet sending ETH to the attacker&#39;s account with a normal transaction fits with the compromise not being limited to Binance 14, but reaching the system that signs for several accounts. But that is inference: the chain only proves the transfer left Binance 16, signed by Binance 16.</li><li><strong>The stablecoins started being converted.</strong> Recipient 1 swapped tokens for ETH on Uniswap (selector 0x791ac947, the swapExactTokensForETHSupportingFeeOnTransferTokens of the V2 router 0x7a250d56…) in hundreds of operations, and moved USDT in blocks of 400-500 M to other EOAs. Recipient 2 did the same with the V3 router.</li></ul><p>And here the limit of this kind of attack shows up when what you steal is centralized stablecoins. Checking the issuers’ blacklists, recipient 1 is already blocked on USDT and USDC, and recipient 2 on USDC:</p><pre># isBlackListed(address) on USDT  -&gt; selector 0xe47d6060<br># isBlacklisted(address) on USDC  -&gt; selector 0xfe575a87<br>curl -s -X POST https://ethereum-rpc.publicnode.com \<br>  -H &#39;content-type: application/json&#39; \<br>  -d &#39;{&quot;jsonrpc&quot;:&quot;2.0&quot;,&quot;id&quot;:1,&quot;method&quot;:&quot;eth_call&quot;,&quot;params&quot;:[{<br>       &quot;to&quot;:&quot;0xdAC17F958D2ee523a2206206994597C13D831ec7&quot;,<br>       &quot;data&quot;:&quot;0xe47d6060000000000000000000000000&#39;\<br>&#39;5227f603c1ee34ce3c06efe6477003bdfccb2f8c&quot;},&quot;latest&quot;]}&#39;<br># -&gt; 0x...01  (blocked)</pre><p>Tether and Circle freeze with an administrative transaction in their contract (the blacklist); the eth_call only checks whether the address is on that list. Once it is, its USDT or USDC are stuck. That explains the rush to swap into ETH on Uniswap over the following hours. Native ETH has no issuer that can freeze it, but whether a token can be frozen depends on its contract: according to TRM Labs, Arbitrum&#39;s Security Council froze 8,426 ETH and 74.6 M ARB on its network. The 823 M of USDC and a good part of the USDT that didn&#39;t get converted in time can be frozen. In practice, part of the loot is already worthless to the attacker.</p><h4>The revocation</h4><p>At 00:10:35 on October 30, Binance 14 sent itself the type 4 transaction <a href="https://etherscan.io/tx/0xafbf94c92a8d749988411669fa14d4f8866d9b4420b4ebd299f28e958dac7209">0xafbf94c9…</a>: a single authorization delegating to 0x0000000000000000000000000000000000000000. Delegating to the zero address is EIP-7702&#39;s canonical way of clearing a delegation. Ten minutes later, the transactions the account sends shoot up again (157 in the 00:20 window), compatible with a return to normal operation; the chain does not prove those 157 were legitimate. Today eth_getCode on Binance 14 returns 0x: the account is an EOA with no code again.</p><p>The chain proves that someone able to sign for Binance 14 signed the revocation at 00:10:35; it does not prove that Binance regained control. Binance 14 kept sending its own transactions during the delegation, and TRM Labs suggests the attacker controlled the signing system and not just a key. According to TRM Labs, Binance had not yet published the root cause. The hole stayed open for 3 hours and 50 minutes. That is a long time for an incident of this size, and why it took almost four hours to close is probably the most uncomfortable question for Binance.</p><h4>What isn’t known</h4><p>With the chain in front of us, these questions stay unanswered, and it is best not to invent answers:</p><ul><li><strong>How the attacker got to sign with the key.</strong> The chain proves the 50 signatures are Binance 14’s, not how they were obtained. Binance says the attacker <em>may</em> have used a compromised DevOps engineer’s laptop to get into its internal infrastructure (<a href="https://cointelegraph.com/news/binance-hack-may-involve-private-key-misuse-not-theft-blockaid-ceo">Cointelegraph</a>, October 30). That is a hypothesis of theirs, not a fact, and it later said it had found more entry points (<a href="https://decrypt.co/382203/binance-finds-additional-points-of-breach-in-6-3b-hack">Decrypt</a>). I can’t verify it on-chain.</li><li><strong>Whether Binance 16 was equally compromised or was just used as a stepping stone.</strong> The 28,005 ETH transfer is normal and signed by Binance 16, nothing more.</li><li><strong>The real total and the other chains.</strong> My 3,200 M is Ethereum only, and only what I could add up. The 6,300 M comes from the press (<a href="https://cointelegraph.com/news/binance-hack-may-involve-private-key-misuse-not-theft-blockaid-ceo">Cointelegraph</a>, <a href="https://decrypt.co/382203/binance-finds-additional-points-of-breach-in-6-3b-hack">Decrypt</a>); according to <a href="https://decrypt.co/382224/trm-and-chainalysis-tie-6-4b-binance-hack-to-north-koreas-tradertraitor">Decrypt</a>, Chainalysis puts it at 6,400 M and TRM at 6,360 M (as <a href="https://www.trmlabs.com/resources/blog/north-korea-steals-usd-6-36-billion-from-binance-in-the-largest-hack-in-history">its own blog</a> also says); and Binance says it has set aside 6,340 M to cover losses (<a href="https://decrypt.co/382237/binance-sets-aside-6-34b-to-cover-hack-losses-ceo-says-your-assets-are-safe">Decrypt</a>).</li><li><strong>The attribution.</strong> TraderTraitor, a North Korean group that <a href="https://www.cisa.gov/news-events/cybersecurity-advisories/aa22-108a">CISA</a> links to Lazarus, is the claim of <a href="https://www.trmlabs.com/resources/blog/north-korea-steals-usd-6-36-billion-from-binance-in-the-largest-hack-in-history">TRM Labs</a> and <a href="https://www.chainalysis.com/blog/binance-exploit-latest-findings-and-response/">Chainalysis</a>. Using Tornado Cash to fund the gas and the consolidation pattern are compatible with state-backed groups, but “compatible with” is not “is”. The use of 7702 with batched authorizations, specifically, has been seen this year in automated drainers aimed at ordinary users’ wallets, not only in large operations.</li></ul><h4>Lessons for exchanges and custodians</h4><p>The protocol worked as written. The failure is upstream, in how an organization signs and what it watches. What this case makes clear:</p><p><strong>EIP-7702 turns a stolen signature into persistent access.</strong> Before, stealing a signature got you one transaction. Now, stealing a 7702 authorization gets you the account until someone revokes it. The threat model of anyone who holds keys changed on May 7, 2025, whether they knew it or not.</p><p><strong>Signing policy must reject unexpected EIP-7702 authorizations.</strong> A deposit account has no legitimate reason to sign a delegation authorization. The type 4 transaction and the signed authorization are different objects: 0xad99… was signed and sent by the operator, and Binance 14 only signed the authorizations. The control belongs on the signer: the HSM or signing service should refuse to sign 7702 authorization tuples except the expected and reviewed ones (TRM Labs recommends rejecting EIP-7702 authorizations that are not expected). If Binance’s signing flow had rejected them for its hot wallets, these 50 signatures would not have existed.</p><p><strong>You have to monitor EOA code.</strong> A hot wallet that suddenly has code (eth_getCode stops returning 0x) is a top-priority alarm. It is cheap: a cron job that queries eth_getCode for every hot account every few seconds and alerts if it changes. That is what cuts the 3 hours and 50 minutes down to minutes, with a limit: polling only sees delegations that are active at the moment of the query, and one that is set and removed between two polls slips through. A minimal detection rule:</p><pre>import json, subprocess<br><br>RPC = &quot;https://ethereum-rpc.publicnode.com&quot;<br>HOT_WALLETS = [&quot;0x28C6c06298d514Db089934071355E5743bf21d60&quot;]  # add yours<br><br><br>def alert(msg):  # your own alerting channel (pager, Slack...)<br>    print(msg)<br><br>def code_of(addr):<br>    body = {&quot;jsonrpc&quot;:&quot;2.0&quot;,&quot;id&quot;:1,&quot;method&quot;:&quot;eth_getCode&quot;,&quot;params&quot;:[addr,&quot;latest&quot;]}<br>    out = subprocess.run([&quot;curl&quot;,&quot;-s&quot;,&quot;-X&quot;,&quot;POST&quot;,RPC,<br>                          &quot;-H&quot;,&quot;content-type: application/json&quot;,<br>                          &quot;-d&quot;,json.dumps(body)], capture_output=True, text=True).stdout<br>    return json.loads(out)[&quot;result&quot;]<br><br>for w in HOT_WALLETS:<br>    code = code_of(w)<br>    # EIP-7702: a delegated EOA starts with the 0xef0100 designator<br>    if code != &quot;0x&quot;:<br>        delegate = &quot;0x&quot; + code[8:] if code.startswith(&quot;0xef0100&quot;) else None<br>        alert(f&quot;{w} has code: {code[:20]}… delegated to {delegate}&quot;)</pre><p>There is no delegation event to listen for with eth_getLogs. The finer approach is to walk every block (eth_getBlockByNumber with full transactions), look at the type 4 ones and recover the signer (authority) of each authorization with ecrecover over keccak(0x05 || rlp([chain_id, address, nonce])), because that field is not in the transaction. That also catches a delegation set and removed between two eth_getCode polls.</p><p><strong>Response time matters as much as prevention.</strong> The attacker built a sweep loop precisely because they knew the account would keep receiving deposits. Every minute the delegation was in place, new money arrived and left. An automatic deposit cutoff on detecting code in a hot wallet would have stopped the bleeding even without an instant revocation.</p><p><strong>Centralized stablecoins are the attacker’s weak point, not yours.</strong> That Tether and Circle froze the recipients within hours is the best news of the incident. If your exchange has a relationship with the issuers, the window to ask for a freeze is measured in minutes, and every minute counts before the attacker swaps to ETH on a DEX.</p><h4>How to reproduce the checks</h4><p>All of this can be verified without an API key. The delegation:</p><pre>curl -s https://eth.blockscout.com/api/v2/transactions/\<br>0xad99264d5532ae0dd04b2004eebda05f25657e70dacb764f7ac8d4ccd051298b \<br>  | python3 -c &#39;import json,sys; t=json.load(sys.stdin); al=t[&quot;authorization_list&quot;]; \<br>print(&quot;authorizations:&quot;,len(al)); \<br>print(&quot;ok:&quot;,[int(a[&quot;nonce&quot;]) for a in al if a[&quot;status&quot;]==&quot;ok&quot;])&#39;<br># authorizations: 50<br># ok: [18914809]</pre><p>The sweeper’s bytecode and its disassembly:</p><pre>curl -s -X POST https://ethereum-rpc.publicnode.com \<br>  -H &#39;content-type: application/json&#39; \<br>  -d &#39;{&quot;jsonrpc&quot;:&quot;2.0&quot;,&quot;id&quot;:1,&quot;method&quot;:&quot;eth_getCode&quot;,<br>       &quot;params&quot;:[&quot;0x63e842B054Bd624a465454D533C33F573e9c6fAe&quot;,&quot;latest&quot;]}&#39; \<br>  | python3 -c &#39;import json,sys; print(json.load(sys.stdin)[&quot;result&quot;])&#39; &gt; sweeper.hex<br>python3 -c &#39;from pyevmasm import disassemble_all; \<br>print(&quot;\n&quot;.join(str(i) for i in disassemble_all(bytes.fromhex(open(&quot;sweeper.hex&quot;).read()[2:]))))&#39;</pre><p>And that Binance 14 is no longer delegated:</p><pre>curl -s -X POST https://ethereum-rpc.publicnode.com \<br>  -H &#39;content-type: application/json&#39; \<br>  -d &#39;{&quot;jsonrpc&quot;:&quot;2.0&quot;,&quot;id&quot;:1,&quot;method&quot;:&quot;eth_getCode&quot;,<br>       &quot;params&quot;:[&quot;0x28C6c06298d514Db089934071355E5743bf21d60&quot;,&quot;latest&quot;]}&#39;<br># {&quot;result&quot;:&quot;0x&quot;}</pre><h4>Conclusion</h4><p>There was no failure in Ethereum, or in EIP-7702, or even in the attacker’s contract, which is almost insultingly simple: 1,674 bytes, five functions, zero state. What failed was the usual link, key custody, but with a new difference that changes the math. Since Pectra, a single signature pulled from a hot wallet is no longer worth just one transaction or one token; it is worth the whole account, for as long as it takes them to notice.</p><p>The 50-authorization trick is elegant and cheap: it costs 25,000 gas per attempt, and only one needs to hit the nonce. Anyone who custodies keys on Ethereum has to assume that signing an EIP-7702 authorization is, in effect, handing over the account, and treat that signature with the care that deserves: reject it by default, watch the code of their EOAs, and have a kill switch that doesn’t depend on recovering the key first.</p><p>The good part is that the money leaves a public trail that anyone can follow with curl, and that centralized stablecoins can be frozen. The bad part is that the door stood open for 3 hours and 50 minutes. Binance says it has set aside 6,340 M to cover the losses and that users&#39; funds are safe.</p><p><em>Corrected on November 1, 2026: authorization order, msg.sender, attribution (TraderTraitor), scope of the monitoring and other nuances. Thanks to whoever reviewed it.</em></p><p><em>Originally published on my blog: </em><a href="https://blog.danielalfocea.com/en/robo-binance-hot-wallet-eip-7702/"><em>https://blog.danielalfocea.com/en/robo-binance-hot-wallet-eip-7702/</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=becd5588e542" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Lua Scripts in Redis: The Ping Pong Example]]></title>
            <link>https://cr0hn.medium.com/understanding-lua-scripts-in-redis-the-ping-pong-example-b7f959072535?source=rss-e88f464b9d9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7f959072535</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[lua]]></category>
            <dc:creator><![CDATA[Daniel Alfocea]]></dc:creator>
            <pubDate>Tue, 14 May 2024 09:30:36 GMT</pubDate>
            <atom:updated>2024-05-14T09:30:36.018Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MjK9zZTadGRJP5Kc" /></figure><p>A time ago, <a href="https://www.linkedin.com/pulse/understanding-lua-scripts-redis-ping-pong-example-garcia-cr0hn--ziddf/">I posted a question about Lua scripting</a> in Redis on my LinkedIn and shared a snippet that sparked my curiosity. For those who missed it, here’s the Lua script I shared:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/0*2u29vjAuX4US-jWw" /></figure><p>At first glance, this script exemplifies the “ping-pong” programming pattern, where one function calls the other in an infinite loop. This type of script is often used to demonstrate or test recursion and function calls.</p><p>The expected behavior is that these functions will call each other indefinitely, leading to an infinite loop. In many programming environments, such a script would cause the system to eventually crash or hit predefined security limits, such as soft or hard caps set by the system administrator.</p><p>However, when this script is executed in Redis, the result is quite different and interesting. Redis supports Lua scripting, allowing for powerful data manipulations and direct computations within the database. However, Redis also incorporates a secure execution environment to handle Lua scripts. This environment includes several safeguards to prevent scripts from causing harm, intentionally or accidentally.</p><p>When the provided Lua script is executed in Redis, it doesn’t lead to an infinite loop or a system crash. Instead, Redis detects the potentially dangerous pattern and halts the execution. Here’s what happens:</p><p>Redis has built-in protections that recognize the script&#39;s recursion pattern. The secure Lua environment in Redis is designed to catch and prevent such infinite loops from running. This stops the script from consuming resources endlessly, ensuring the system&#39;s stability and security.</p><p>Essentially, Redis enforces a read-only table restriction in this context, which prevents modifications that could lead to uncontrolled recursion.</p><p>Here’s a screenshot showing the exact response from Redis when this script is executed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hZzsxb2wpHbCrFFs" /></figure><p>As the screenshot indicates, Redis throws an error: “Attempt to modify a read-only table script.” This error message shows that Redis has detected an attempt to execute a potentially harmful recursive function and has prevented it from proceeding. This built-in safety mechanism is a testament to Redis’s robust design, which prioritizes security and stability.</p><p>Redis’s handling of Lua scripts underscores its capabilities as a secure and reliable database management system. By preventing infinite loops and potentially harmful scripts from running, Redis ensures that the database remains operational and efficient, even when users execute complex scripts.</p><p>This behavior is particularly important in production environments with critical stability and uptime. Developers can write and execute Lua scripts with the confidence that Redis will enforce safeguards to maintain system integrity. Redis’s ability to manage these scripts securely makes it an invaluable tool for developers looking to perform complex data operations directly within the database.</p><p>Redis, a marvel of modern database technology, continues proving its worth with these robust features. Its ability to handle potentially dangerous scripts gracefully showcases its commitment to providing a secure, high-performance environment for data management.</p><p>Once again, Redis is an incredible technology, ensuring security and stability even when faced with potentially problematic scripts. Redis is truly a marvel!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7f959072535" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cyclomatic Complexity in Software Development and Its Impact on Cybersecurity]]></title>
            <link>https://cr0hn.medium.com/cyclomatic-complexity-in-software-development-and-its-impact-on-cybersecurity-bcf972322832?source=rss-e88f464b9d9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcf972322832</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[devsecops]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Daniel Alfocea]]></dc:creator>
            <pubDate>Thu, 15 Feb 2024 11:58:51 GMT</pubDate>
            <atom:updated>2024-02-15T11:58:51.654Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*bXWnHPRbLL6NU0unm-8C7A.jpeg" /></figure><h4>Understanding Cyclomatic Complexity</h4><h4>Introduction</h4><p>The concept of cyclomatic complexity, introduced by Thomas J. McCabe in 1976(http://www.literateprogramming.com/mccabe.pdf), is crucial for grasping code complexity and plays a significant role in cybersecurity.</p><p>This article will delve into cyclomatic complexity, its effects on code quality, and its connection to cybersecurity. We’ll also explore examples of how cyclomatic complexity can impact software security and ways to mitigate its risks.</p><h4>Grasping Cyclomatic Complexity</h4><p>Cyclomatic complexity measures the number of independent execution paths through a program’s source code.</p><p>Fundamentally, it assesses software’s flow control complexity by counting decision-making structures like if, else, switch, while, and for statements.</p><p>A higher cyclomatic complexity score signals more complex code, which can be more challenging to understand and maintain.</p><h4>Cyclomatic Complexity and Code Quality</h4><p>Code with high cyclomatic complexity often indicates poor quality. It’s more error-prone due to its challenging readability, comprehension, and modification. In software development, simpler code is typically preferred as it’s easier to maintain and less likely to contain errors.</p><p>Let’s examine some examples to illustrate better how cyclomatic complexity can influence code quality.</p><h4>Python example</h4><p><strong>Bad complexity</strong></p><p>Here, a code snippet performs multiple tasks with multiple conditions, making it hard to understand and maintain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*f4eMPS6yLO7KpxosvhNuVQ.png" /></figure><p><strong>Good complexity</strong></p><p>Decomposing functions into smaller, more specific parts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*yfgtzEHOg9jeVVaaBSu69g.png" /></figure><p>The cyclomatic complexity is significantly reduced by breaking down the original function into smaller, more specific parts. Each function is responsible for a particular task, making the code more readable and easier to maintain.</p><h4>Golang example</h4><p><strong>Bad complexity</strong></p><p>This code has multiple branching and nested conditions, significantly increasing its cyclomatic complexity. This makes it difficult to understand, test, and maintain. Each new condition adds one more path through the code, raising the possibility of errors and making it harder to detect security issues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*swD3dZt9xSFLPDEAnOrLqQ.png" /></figure><p><strong>Good complexity</strong></p><p>This code has been refactored to reduce its cyclomatic complexity. Parts of the logic have been extracted into separate functions, making each function more straightforward and with a single responsibility.</p><p>Using switch and separate functions makes the code easier to understand and maintain, as well as to test and debug.</p><p>This structure also makes identifying and rectifying potential security vulnerabilities easier, as each function focuses on a specific aspect of the risk evaluation logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*CEJYcO91aaiQ6qL8r5C8OA.png" /></figure><h4>Cyclomatic Complexity and Cybersecurity</h4><p>High cyclomatic complexity can significantly impact the cybersecurity of software. Here are some ways in which high cyclomatic complexity can affect software security:</p><ol><li><strong>Human Errors</strong>: More complex code is more complicated to understand, making it more prone to errors during development and maintenance. These errors can create unintended vulnerabilities.</li><li><strong>Code Review Challenges</strong>: Code review is crucial for identifying vulnerabilities. High cyclomatic complexity can make code reviews more challenging and less effective.</li><li><strong>Testing and Code Analysis</strong>: Automated testing and code analysis tools may struggle to analyze codes with high complexity properly, leaving potential vulnerabilities undetected.</li></ol><h4>Cyclomatic Complexity and Security Failures</h4><p>Security failures often stem from coding errors. High cyclomatic complexity increases the likelihood of security flaws. Some common vulnerabilities related to cyclomatic complexity include:</p><ul><li><strong>SQL Injections</strong>: Complex codes may not properly handle user inputs, leading to SQL injection vulnerabilities.</li><li><strong>Buffer Overflow Errors</strong>: Excessive complexity in data handling can lead to poor boundary checks, resulting in buffer overflow errors.</li><li><strong>Authentication and Session Management Failures</strong>: Complex codes in authentication systems can contain critical flaws, compromising user security.</li><li><strong>Access Control Issues</strong>: High cyclomatic complexity can lead to errors in permission management and access control, often the source of vertical privilege escalations.</li><li><strong>Code Injection Vulnerabilities</strong>: High cyclomatic complexity can lead to complex flow control, resulting in code injection vulnerabilities due to poor management of user inputs.</li><li><strong>Session Management Issues</strong>: High cyclomatic complexity can lead to session management and authentication errors, often the source of horizontal privilege escalations.</li></ul><p>While there are other vulnerabilities, these are some of the most common ones related to cyclomatic complexity.</p><h4>Examples of Vulnerabilities Related to Cyclomatic Complexity (Python)</h4><h4>Web Authentication Flows</h4><p><strong>High Cyclomatic Complexity</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*IFqns3WPySPU0_hfsjPPOA.png" /></figure><p>In the following example, a complex authentication code may contain security vulnerabilities. High cyclomatic complexity can make it harder to detect and correct these vulnerabilities.</p><ul><li>This code has high cyclomatic complexity due to multiple nested conditions and branches.</li><li>It uses MD5 for the password, which is not secure.</li><li>Password validation is performed after verifying if the user exists and the password matches, which is not a recommended practice.</li></ul><p><strong>Low Cyclomatic Complexity</strong></p><p>In this example, the authentication code has been simplified and refactored to reduce cyclomatic complexity. This makes it easier to understand, test, and maintain, decreasing the likelihood of security vulnerabilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*qR-wL0qget2rK4rpKaMWeg.png" /></figure><ul><li>Cyclomatic complexity is significantly reduced due to the elimination of unnecessary nested conditions.</li><li>Uses werkzeug.security.check_password_hash for a more secure password verification.</li><li>It improves security by not revealing whether a specific username exists or not.</li></ul><h4>Command execution</h4><p><strong>High Cyclomatic Complexity</strong></p><p>This example demonstrates a script that performs operations based on user input, with a complex control structure and a critical vulnerability:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*LSWm9f7mGd5hG5O8bzy3Sw.png" /></figure><ul><li>This code has high cyclomatic complexity due to multiple decision branches.</li><li>It uses os.system, which is dangerous if combined with unsanitized inputs, allowing the execution of arbitrary commands.</li></ul><p><strong>Low Cyclomatic Complexity</strong></p><p>Here’s a safer approach with lower cyclomatic complexity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Au9cyL8uIh1efR4daw7VjQ.png" /></figure><ul><li>The cyclomatic complexity is reduced by breaking the logic into smaller, clearer functions.</li><li>It uses subprocess.run, is safer than os.system`, and prevents insecure command execution.</li><li>Separating the operations into different functions makes the code easier to understand and maintain.</li></ul><h4>Examples of Vulnerabilities Related to Cyclomatic Complexity (Golang)</h4><h4>Arbitrary Command Execution</h4><p>This example in Go demonstrates a function that processes user input to execute system commands. The complexity arises from multiple conditional branches and direct command execution based on user input.</p><p><strong>High Cyclomatic Complexity</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*kgmR3XN-dPnVtDm7nkDTrw.png" /></figure><ul><li>The function executeCommand processes user input and directly executes system commands based on this input.</li><li>Using exec.Command with unsanitized user input introduces a significant security risk, as it can lead to arbitrary command execution.</li><li>The complexity of handling different commands in the same function increases the risk of errors and makes the code harder to audit for security issues.</li></ul><p><strong>Low cyclomatic complexity</strong></p><p>Here’s a safer approach with lower cyclomatic complexity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*7iiVORgUk4jtjKU9-r_grQ.png" /></figure><ul><li>By breaking down the original executeCommand function into smaller functions (executeEcho and listDirectory), the cyclomatic complexity is significantly reduced.</li><li>Each function is responsible for a specific task, making the code more readable and easier to maintain.</li><li>Although the use of exec.Command still poses risks. Separating commands into dedicated functions allows for more controlled and secure user input handling.</li></ul><h4>Optimal Cyclomatic Complexity Values</h4><p>The ideal values for cyclomatic complexity vary depending on the context and programming language. Generally, a cyclomatic complexity value of 10 or less is desirable for maintaining clear and easily understandable code.</p><p>From my experience, cyclomatic complexity values can be categorized in terms of safety as follows:</p><ul><li><strong>1–10</strong>: Regarded as an ideal range. Code within this range is typically easy to understand and maintain. Testing is more straightforward, and the likelihood of introducing security flaws is lower.</li><li><strong>10–20</strong>: Indicates moderate complexity. While not ideal, it’s manageable. Rigorous testing and code reviews are important to ensure quality and security.</li><li><strong>20–40</strong>: Considered a high level of complexity. Code in this range can be challenging to understand and test properly, increasing the risk of errors and vulnerabilities.</li><li><strong>&gt;40</strong>: Extremely complex and should be avoided. The code is difficult to understand and test, significantly increasing the risk of errors and security vulnerabilities.</li></ul><p>These values should not be taken as strict rules but as general guidelines. Cyclomatic complexity should be assessed in the specific code and project context.</p><h4>Mitigation and Best Practices</h4><p>Cyclomatic complexity is often not considered a metric for secure software development. However, it is an important metric that can significantly impact software security. As demonstrated in the previous examples, high cyclomatic complexity can increase the likelihood of errors and security vulnerabilities.</p><p>The process for measuring cyclomatic complexity and its mitigation can vary depending on the programming language and available tools, although it’s straightforward. Implementing it, however, can be more complex and, in some cases, require significant changes to the code.</p><h4>Measuring Cyclomatic Complexity</h4><p>Measuring cyclomatic complexity is the first step in addressing this issue. Some tools can help measure the cyclomatic complexity of code. Some of these tools include:</p><ul><li><strong>Python</strong>: Radon is an excellent tool for Python. It analyzes source code to calculate cyclomatic complexity, among other metrics like maintainability index. Flake8 can also be used with options to measure cyclomatic complexity.</li><li><strong>Java</strong>: Use Checkstyle with its cyclomatic complexity module. This tool helps adhere to specific coding standards in Java and can calculate cyclomatic complexity for methods and classes.</li><li><strong>JavaScript</strong>: ESLint is a solid choice for JavaScript. Known more as a linter for finding and fixing code issues, it can also be configured to report on cyclomatic complexity.</li><li><strong>C++</strong>: Cppcheck is a static analysis tool that can be used to measure cyclomatic complexity and detect various types of code errors.</li><li><strong>C#</strong>: Visual Studio offers integrated capabilities to analyze cyclomatic complexity directly in the development environment for C#.</li><li><strong>PHP</strong>:</li><li>MD (PHP Mess Detector) helps find coding issues in PHP, including cyclomatic complexity.</li><li>PhpMetrics provides a detailed analysis of PHP code quality, including cyclomatic complexity and other relevant metrics.</li><li><strong>Golang</strong>:</li><li>Gocyclo is specifically designed to calculate the cyclomatic complexity of functions in Go.</li><li>Go Report Card, while broader in its functions, includes a review of cyclomatic complexity as part of its Go code analysis.</li></ul><h4>Mitigation Measures and Best Practices</h4><p>To address cyclomatic complexity and its implications in cybersecurity, the following measures and best practices can be implemented:</p><ul><li><strong>Code Refactoring</strong>: Regularly review and simplify code.</li><li><strong>Rigorous Testing</strong>: Implement automated and manual testing to identify and correct errors.</li><li><strong>Software Design Principles</strong>: Apply principles like SOLID to create more modular and maintainable code.</li><li><strong>Training</strong>: Many developers are unfamiliar with cyclomatic complexity and its impact on security. Training on this topic can help teams understand and address cyclomatic complexity.</li><li><strong>Code Review</strong>: Conduct regular code reviews to identify and correct complexity issues.</li><li><strong>Static Analysis Tools</strong>: Use static analysis tools to identify high-risk areas.</li><li><strong>Automated Security Testing</strong>: Implement automated security testing to detect vulnerabilities.</li></ul><p>The priority order of these measures may vary depending on the context and specific needs of the project. However, if I had to choose one measure, it would be refactoring those parts of the code that are directly linked to user inputs, as this is where most vulnerabilities are found.</p><h4>Conclusions</h4><p>Cyclomatic complexity is a somewhat unknown metric in software development, but it’s an important one that can significantly impact software security.</p><p>This metric is often overlooked as a good practice in secure software development, but it’s an important one that can significantly impact software security.</p><p>Measuring cyclomatic complexity is straightforward, and some tools can help measure the cyclomatic complexity of code. However, its implementation can be more complex and, in some cases, require significant changes to the code. Even in the worst-case scenario, with measurement, we will know which parts of the code are more complex and, therefore, more prone to errors and potential vulnerabilities, allowing us to prioritize and focus our efforts on the most critical areas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcf972322832" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing SSH Server Security: Configuring OTP for SSH Access]]></title>
            <link>https://cr0hn.medium.com/enhancing-ssh-server-security-configuring-otp-for-ssh-access-a65c097bcc8a?source=rss-e88f464b9d9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a65c097bcc8a</guid>
            <category><![CDATA[ssh]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Daniel Alfocea]]></dc:creator>
            <pubDate>Tue, 20 Jun 2023 07:48:39 GMT</pubDate>
            <atom:updated>2023-06-20T07:48:39.287Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*dUY01Z6nrXhJVknZWfGqGQ.jpeg" /></figure><p>If You’re Looking for an effective way to protect your SSH access, In this post, we’ll explore the implementation of One-Time Passwords (OTP) as an additional layer of security for your SSH server.</p><p>Let’s dive into the step-by-step process:</p><h4>Step 1</h4><p>Install libpam-google-authenticator Launch your terminal and execute the following command to install libpam-google-authenticator:</p><pre>$ sudo apt update &amp;&amp; sudo apt install --assume-yes libpam-google-authenticator #Ubuntu and Debian variance</pre><h4>Step 2</h4><p>Modify SSHd Configuration Using your preferred text editor, open the SSHd configuration file:</p><pre>$ sudo vi /etc/ssh/sshd_config</pre><p>Uncomment the line by removing the leading ‘#’ and set the ChallengeResponseAuthentication directive to &#39;yes&#39;:</p><pre>ChallengeResponseAuthentication yes</pre><p>Optionally, you can set the keyboard-interactive authentication method for a specific user by adding the following lines:</p><pre>sqlCopy code<br>Match User username<br>    AuthenticationMethods keyboard-interactive</pre><blockquote>Note: The keyboard-interactive authentication method is enabled by default for all users.</blockquote><h4>Step 3</h4><p>Set Authentication Methods To exclude specific users from using OTP two-factor authentication and allow other authentication methods, modify the SSHd configuration as per your requirements. For example:</p><pre>auth    required      pam_unix.so     no_warn try_first_pass<br>auth    required      pam_google_authenticator.so</pre><h4>Step 4</h4><p>Restart SSH Service. To apply the configuration changes, restart the SSH service:</p><pre>$ sudo systemctl restart ssh</pre><h4>Step 5</h4><p>Configure OTP for Users Edits the PAM configuration file for SSHd:</p><pre>$ sudo vi /etc/pam.d/sshd</pre><p>Add the following lines at the end of the file to enforce password-based login followed by the Google Authenticator module:</p><pre>auth    required      pam_unix.so     no_warn try_first_pass<br>auth    required      pam_google_authenticator.so</pre><h4>Step 6</h4><p>Generate OTP Credentials Run the google-authenticator command to configure and generate the QR code for each user:</p><pre>$ google-authenticator</pre><blockquote>Repeat this step for all other users.</blockquote><p>Follow the prompts and answer ‘y’ to use time-based authentication tokens, scan the generated QR code using an authenticator app, and enter the code generated by the app.</p><h4>Step 7</h4><p>Update Configuration and Policies Answer ‘y’ to update the /home/user/.google\_authenticator file, confirm the single-use of generated time-based tokens, and agree to code generation and usage policies.</p><h4>Step 8</h4><p>Enable Rate-Limiting (Optional) Answer ‘y’ to enable rate-limiting, which limits brute-force login attempts.</p><p>That’s it! You’ve successfully configured OTP two-factor authentication for your SSH server, bolstering its security against potential threats.</p><p>Remember to repeat Step 6 for all users who require access. Following these steps can significantly enhance your server’s security and mitigate the risk of unauthorized access.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a65c097bcc8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redis vs. KeyDB — My Performance Test and Conclusions]]></title>
            <link>https://medium.com/better-programming/redis-vs-keydb-my-performance-test-and-conclusions-519a658ded6e?source=rss-e88f464b9d9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/519a658ded6e</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Daniel Alfocea]]></dc:creator>
            <pubDate>Thu, 15 Dec 2022 10:23:18 GMT</pubDate>
            <atom:updated>2023-02-06T11:11:30.188Z</atom:updated>
            <content:encoded><![CDATA[<h4>Is KeyDB faster than Redis?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*IzhozU0vkUIpIypphJF7YQ.png" /></figure><p>KeyDB is a fork of Redis. KeyDB project claims that the Redis implementation approach is not correct and can be better, in terms of performance.</p><p>KeyDB can run more than one thread, compared to Redis approach which only runs one.</p><p>The <a href="https://docs.keydb.dev/">KeyDB website</a> claims that it’s faster than Redis. I did some quick tests to check the performance as cache server (it means that I tested commands like GET / SET) and in this post I’ll share my results.</p><h3>How Did I Test?</h3><p>For my test, I used Docker for running Redis and KeyDb. I configured my Docker Engine with 4 vCPUs to take the advantage of KeyDB multithreading:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*jDOZmGgXGsBBQGCVuMRm2Q.png" /></figure><p>I also increased the OS limits to allow a high number of concurrent connections for the tests:</p><pre>&gt; ulimit -a<br>-t: cpu time (seconds)              unlimited<br>-f: file size (blocks)              unlimited<br>-d: data seg size (kbytes)          unlimited<br>-s: stack size (kbytes)             8192<br>-c: core file size (blocks)         0<br>-v: address space (kbytes)          unlimited<br>-l: locked-in-memory size (kbytes)  unlimited<br>-u: processes                       11136<br>-n: file descriptors                256</pre><h3>Tests Conditions</h3><p>I did a test with these parameters:</p><ul><li>Total queries: 50.000</li><li>Command tested: GET / SET</li><li>Concurrent clients: 500</li><li>I executed the same test 5 times.</li></ul><h3>KeyDB results</h3><p>KeyDB Version: 6.3.1</p><h4>Server with 4 threads</h4><pre>&gt; docker run -p 6777:6379 eqalpha/keydb keydb-server --server-threads 4</pre><p>Executing tests:</p><pre>&gt; redis-benchmark -p 6777 -t get,set -q -n 50000 -c 500<br>SET: 23775.56 requests per second, p50=14.559 msec<br>GET: 22758.31 requests per second, p50=13.439 msec<br><br>&gt; redis-benchmark -p 6777 -t get,set -q -n 50000 -c 500<br>SET: 18903.59 requests per second, p50=16.247 msec<br>GET: 22872.83 requests per second, p50=13.359 msec<br><br>&gt; redis-benchmark -p 6777 -t get,set -q -n 50000 -c 500<br>SET: 23430.18 requests per second, p50=14.583 msec<br>GET: 20729.69 requests per second, p50=14.687 msec<br><br>&gt; redis-benchmark -p 6777 -t get,set -q -n 50000 -c 500<br>SET: 17325.02 requests per second, p50=19.263 msec<br>GET: 19723.87 requests per second, p50=16.591 msec<br><br>&gt; redis-benchmark -p 6777 -t get,set -q -n 50000 -c 500<br>SET: 25706.94 requests per second, p50=13.191 msec<br>GET: 19817.68 requests per second, p50=14.839 msec</pre><p>As a summary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*cx7s0WSh7MWdJJJ1OYpJGQ.png" /></figure><h4>Server with 2 threads</h4><pre>&gt; docker run -p 6777:6379 eqalpha/keydb keydb-server --server-threads 2</pre><p>Executing tests:</p><pre>&gt; redis-benchmark -p 6777 -t get,set -q -n 50000 -c 500<br>SET: 31605.56 requests per second, p50=11.095 msec<br>GET: 33692.72 requests per second, p50=10.815 msec<br><br>&gt; redis-benchmark -p 6777 -t get,set -q -n 50000 -c 500<br>SET: 30395.14 requests per second, p50=12.271 msec<br>GET: 32959.79 requests per second, p50=13.639 msec<br><br>&gt; redis-benchmark -p 6777 -t get,set -q -n 50000 -c 500<br>SET: 29691.21 requests per second, p50=13.087 msec<br>GET: 32467.53 requests per second, p50=13.159 msec<br><br>&gt; redis-benchmark -p 6777 -t get,set -q -n 50000 -c 500<br>SET: 28216.71 requests per second, p50=14.295 msec<br>GET: 30693.68 requests per second, p50=14.103 msec<br><br>&gt; redis-benchmark -p 6777 -t get,set -q -n 50000 -c 500<br>SET: 31486.14 requests per second, p50=12.543 msec<br>GET: 35087.72 requests per second, p50=12.543 msec</pre><p>As a summary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Usy0Wmg7xkwMBUtqWca4FQ.png" /></figure><h4>Server with 1 thread</h4><p>I did tests with only one thread, but the results were the same as with 2 threads.</p><h3>Redis Results</h3><p>Redis Version: 7.0.2</p><p>Executing server:</p><pre>&gt; docker run -p 6379:6379 redis</pre><p>Executing tests:</p><pre>&gt; redis-benchmark -p 6379 -t get,set -q -n 50000 -c 500<br>SET: 37622.27 requests per second, p50=12.527 msec<br>GET: 28392.96 requests per second, p50=12.919 msec<br><br>&gt; redis-benchmark -p 6379 -t get,set -q -n 50000 -c 500<br>SET: 27442.37 requests per second, p50=13.439 msec<br>GET: 31446.54 requests per second, p50=15.527 msec<br><br>&gt; redis-benchmark -p 6379 -t get,set -q -n 50000 -c 500<br>SET: 27808.68 requests per second, p50=13.751 msec<br>GET: 35335.69 requests per second, p50=13.391 msec<br><br>&gt; redis-benchmark -p 6379 -t get,set -q -n 50000 -c 500<br>SET: 30156.82 requests per second, p50=14.631 msec<br>GET: 37009.62 requests per second, p50=12.711 msec<br><br>&gt; redis-benchmark -p 6379 -t get,set -q -n 50000 -c 500<br>SET: 33068.79 requests per second, p50=13.359 msec<br>GET: 40225.26 requests per second, p50=10.999 msec</pre><p>As a summary:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*H6PAqfwqs9uo3Mz1siZoxA.png" /></figure><h3>Conclusion</h3><p>Ok. Results are curious:</p><ol><li>KeyDB says that they are faster than Redis because they can run in a multithreading way, but in tests, results appear that it runs faster when the number of threads tens to 1… like Redis.</li><li>This means that KeyDB needs more resources to reach the same performance as Redis.</li><li>KeyDB threads need to count your hardware resources; otherwise, Redis.</li></ol><p>We also have to keep in mind that KeyDB has a great feature that Redis doesn’t have (at least in their Open-Source version) like:</p><p>The<em> “</em>On Flash” feature. This feature uses SSD disks as an extension of RAM, spending less RAM with very similar performance.</p><ul><li>Redis on flash: <a href="https://redis.com/redis-enterprise/technology/redis-on-flash/">https://redis.com/redis-enterprise/technology/redis-on-flash/</a></li><li>KeyDb on flash: <a href="https://docs.keydb.dev/docs/flash/">https://docs.keydb.dev/docs/flash/</a></li></ul><blockquote>I tried to run KeyDB server with <em>On Flash</em> feature, but I couldn’t. It raised me the error: “FLASH Is Not yet Supported”.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=519a658ded6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/redis-vs-keydb-my-performance-test-and-conclusions-519a658ded6e">Redis vs. KeyDB — My Performance Test and Conclusions</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[Wonderful Python Libraries series Nº 2 :: Python Secure Secret Storage]]></title>
            <link>https://cr0hn.medium.com/wonderful-python-libraries-series-n%C2%BA-2-python-secure-secret-storage-aa135ceafe07?source=rss-e88f464b9d9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa135ceafe07</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[vault]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Daniel Alfocea]]></dc:creator>
            <pubDate>Mon, 29 Aug 2022 10:26:07 GMT</pubDate>
            <atom:updated>2022-08-29T10:26:07.640Z</atom:updated>
            <content:encoded><![CDATA[<h3>Wonderful Python Libraries series Nº 2 :: Python Secure Secret Storage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FsVeOpg6eipIhkqFdIHNkQ.jpeg" /></figure><p>Treat with sensitive information is a must. But every so often, it is not easy.</p><p>Today we’ll review the secure secret manager and an easy way to use, a light way solution for some scenarios and local scripts.</p><h4>TL;DR What’s a Secure Secret Storage</h4><p>A vault is a secure storage for saving sensitive data, like passwords, access tokens, etc.</p><p>You also can find this concept by searching for <em>Secret Manager</em>.</p><p>Almost all most known cloud providers have solutions for storing sensitive data securely:</p><ul><li>AWS: <a href="https://aws.amazon.com/es/secrets-manager/">AWS Secret Manager</a></li><li>Google Cloud: <a href="https://cloud.google.com/secret-manager?hl=en">Google Cloud Secret Manager</a></li><li>Azure: <a href="https://azure.microsoft.com/en-us/services/key-vault/">Key Vault</a></li></ul><p>They’re also open source solutions. Most known is <a href="https://www.vaultproject.io/">Hashicorp Vault</a></p><p>All of the above solutions are client-server-based. It’s good. But sometimes, we need something more lightweight.</p><h4>This library, in a few words</h4><p>With Python keyring you can safely store sensitive data.</p><p>This library uses the operating system’s secure storage for saving sensitive data.</p><h4>Some examples</h4><p>Let’s say we want to store Postgres credentials by using this library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*1N5zhTye178wo5y5fR3qrQ.png" /></figure><p>Then, let’s say we would like to use these credentials with our script that connects with a PostgreSQL database.</p><p>First, install the PostgreSQL dependency:</p><pre>&gt; pip install &quot;psycopg[binary]&quot;</pre><p>Then, connect to the database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*JRhmdBQCN8LcpJGH7IUCTA.png" /></figure><p>That’s it! Easy.</p><p>Finally, we can check that the secrets were stored in our Operating System’s secure storage. In my case, I use OS X. So. The sensitive data are stored at Keychain Access:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*3Gixm4UvcbZiW1Un51v7Sw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*lgcPruSSu7g8qWDfUgiF-g.png" /></figure><p>You can found code examples in my GitHub Medium repository:</p><p><a href="https://github.com/cr0hn/my-medium-posts-resources/tree/main/WonderfulLibraries/post-2">https://github.com/cr0hn/my-medium-posts-resources/tree/main/WonderfulLibraries/post-2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa135ceafe07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient memory usage in Python with Zero-copy]]></title>
            <link>https://cr0hn.medium.com/efficient-memory-usage-in-python-with-zero-copy-5ce7a27ce9ef?source=rss-e88f464b9d9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ce7a27ce9ef</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Daniel Alfocea]]></dc:creator>
            <pubDate>Mon, 22 Aug 2022 11:57:59 GMT</pubDate>
            <atom:updated>2022-08-22T11:57:59.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*f-T9Ibgib2zytrSPorPLvA.jpeg" /></figure><p>Python has a lot of magic with memory under the hood and, in most cases, Inefficiently.</p><p>A simple task that reads a file in chunks is inefficient if you don’t take some things in the count.</p><p>Let’s say we have this code:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528255%252C255%252C255%252C1%2529%26t%3Dmonokai%26wt%3Dnone%26l%3Dpython%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%252523%252520file%25253A%252520demo-2.py%25250A%25250Afrom%252520pygments.lexers.html%252520import%252520HtmlLexer%25250Afrom%252520prompt_toolkit.shortcuts%252520import%252520prompt%25250Afrom%252520prompt_toolkit.lexers%252520import%252520PygmentsLexer%25250A%25250Atext%252520%25253D%252520prompt%2528%2527Hi%252520Medium%2521%252520Enter%252520HTML%25253A%252520%2527%25252C%252520lexer%25253DPygmentsLexer%2528HtmlLexer%2529%2529%25250Aprint%2528%2527You%252520wrote%25253A%252520%252525s%2527%252520%252525%252520text%2529&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528255%25252C255%25252C255%25252C1%252529%26t%3Dmonokai%26wt%3Dnone%26l%3Dpython%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25252523%25252520file%2525253A%25252520demo-2.py%2525250A%2525250Afrom%25252520pygments.lexers.html%25252520import%25252520HtmlLexer%2525250Afrom%25252520prompt_toolkit.shortcuts%25252520import%25252520prompt%2525250Afrom%25252520prompt_toolkit.lexers%25252520import%25252520PygmentsLexer%2525250A%2525250Atext%25252520%2525253D%25252520prompt%252528%252527Hi%25252520Medium%252521%25252520Enter%25252520HTML%2525253A%25252520%252527%2525252C%25252520lexer%2525253DPygmentsLexer%252528HtmlLexer%252529%252529%2525250Aprint%252528%252527You%25252520wrote%2525253A%25252520%25252525s%252527%25252520%25252525%25252520text%252529&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f388afd2603d08ec9dc2eadb46a371a5/href">https://medium.com/media/f388afd2603d08ec9dc2eadb46a371a5/href</a></iframe><p>The reading operation allocates 10 MB, and the second operation, content_to_write, creates a memory copy of the first 1024 elements in memory. Remember the Python magic? Here it is :)</p><p>We can use Zero-copy to improve these kinds of tasks.</p><p>Zero-copy is a method to copy data from the disk/network to the memory without passing through the CPU. So, it’s speedy and efficient.</p><p>In Python, you can use Zero-copy by using memoryview.</p><p>Consider the above code using zero-copy:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcarbon.now.sh%2Fembed%3Fbg%3Drgba%2528255%252C255%252C255%252C1%2529%26t%3Dmonokai%26wt%3Dnone%26l%3Dpython%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%2525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%252523%252520file%25253A%252520demo-2.py%25250A%25250Afrom%252520pygments.lexers.html%252520import%252520HtmlLexer%25250Afrom%252520prompt_toolkit.shortcuts%252520import%252520prompt%25250Afrom%252520prompt_toolkit.lexers%252520import%252520PygmentsLexer%25250A%25250Atext%252520%25253D%252520prompt%2528%2527Hi%252520Medium%2521%252520Enter%252520HTML%25253A%252520%2527%25252C%252520lexer%25253DPygmentsLexer%2528HtmlLexer%2529%2529%25250Aprint%2528%2527You%252520wrote%25253A%252520%252525s%2527%252520%252525%252520text%2529&amp;display_name=Carbon&amp;url=https%3A%2F%2Fcarbon.now.sh%2F%3Fbg%3Drgba%252528255%25252C255%25252C255%25252C1%252529%26t%3Dmonokai%26wt%3Dnone%26l%3Dpython%26width%3D680%26ds%3Dtrue%26dsyoff%3D20px%26dsblur%3D68px%26wc%3Dtrue%26wa%3Dtrue%26pv%3D56px%26ph%3D56px%26ln%3Dfalse%26fl%3D1%26fm%3DHack%26fs%3D14px%26lh%3D133%252525%26si%3Dfalse%26es%3D2x%26wm%3Dfalse%26code%3D%25252523%25252520file%2525253A%25252520demo-2.py%2525250A%2525250Afrom%25252520pygments.lexers.html%25252520import%25252520HtmlLexer%2525250Afrom%25252520prompt_toolkit.shortcuts%25252520import%25252520prompt%2525250Afrom%25252520prompt_toolkit.lexers%25252520import%25252520PygmentsLexer%2525250A%2525250Atext%25252520%2525253D%25252520prompt%252528%252527Hi%25252520Medium%252521%25252520Enter%25252520HTML%2525253A%25252520%252527%2525252C%25252520lexer%2525253DPygmentsLexer%252528HtmlLexer%252529%252529%2525250Aprint%252528%252527You%25252520wrote%2525253A%25252520%25252525s%252527%25252520%25252525%25252520text%252529&amp;image=https%3A%2F%2Fcarbon.now.sh%2Fstatic%2Fbrand%2Fbanner.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;scroll=auto&amp;schema=carbon" width="1024" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f388afd2603d08ec9dc2eadb46a371a5/href">https://medium.com/media/f388afd2603d08ec9dc2eadb46a371a5/href</a></iframe><p>In this case, the reading operation allocates <strong>10 MB</strong> and reuses it because it doesn’t copy data ton content_to_write. Instead, it copies a reference.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ce7a27ce9ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wonderful Python Libraries series Nº 1 :: Prompt Toolkit]]></title>
            <link>https://cr0hn.medium.com/wonderful-python-libraries-series-n%C2%BA-1-prompt-toolkit-e6e73d30891a?source=rss-e88f464b9d9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6e73d30891a</guid>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[cli]]></category>
            <dc:creator><![CDATA[Daniel Alfocea]]></dc:creator>
            <pubDate>Sat, 20 Aug 2022 13:38:20 GMT</pubDate>
            <atom:updated>2022-08-20T13:38:20.306Z</atom:updated>
            <content:encoded><![CDATA[<h3>Wonderful Python Libraries series Nº 1 :: Prompt Toolkit</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*SXJBLNRCeH5kyskm0lHZnQ.png" /></figure><p>Today I start a new series of posts with my favorite Python libraries. I’ll share with you those that, I think, is most interesting.</p><p>In this post, I’ll present the library: Prompt Toolkit.</p><p>If you like CLI and terminals for writing your tools, You’ll like this library.</p><p>https://python-prompt-toolkit.readthedocs.io/en/master/index.html</p><h4>This library, in a few words</h4><p>With Prompt toolkit, you can create a rich console UI. Some of their features are:</p><ul><li>Integrated auto-completion and auto-suggestion.</li><li>Integrated syntax highlighting support.</li><li>Integrated session history.</li><li>Key binding</li><li>Ncurses abstraction in Python.</li><li>Real-time progress bars with ncurses.</li><li>Parallel progress bars.</li><li>Create full-screen console apps.</li><li>Hooks.</li><li>Asyncio support.</li><li>Deadline support.</li><li>And more!</li></ul><h4>Some examples</h4><h4>A REPL with steroids</h4><p>Creating a powerful REPL is straightforward. You can add syntax highlighting in the prompt in real time! Just great.</p><pre>from pygments.lexers.html import HtmlLexer<br>from prompt_toolkit.shortcuts import prompt<br>from prompt_toolkit.lexers import PygmentsLexer<br><br>text = prompt(&#39;Hi Medium! Enter HTML: &#39;, lexer=PygmentsLexer(HtmlLexer))<br>print(&#39;You wrote: %s&#39; % text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*w9sssclEFhbj7BORPzRhSQ.png" /></figure><h4>Ncurses dialogs and more</h4><p>With Prompt toolkit, you can do excellent command line interfaces without the need to write ncurses code. It has shortcuts for creating dialogs, checkboxes, radio boxes, and more.</p><p>Here is an easy example:</p><pre>from prompt_toolkit.shortcuts import radiolist_dialog<br><br>result = radiolist_dialog(<br>    title=&quot;Hi Medium!&quot;,<br>    text=&quot;What&#39;s your favorite IDE?&quot;,<br>    values=[<br>        (&quot;pycharm&quot;, &quot;PyCharm&quot;),<br>        (&quot;vscode&quot;, &quot;Vistual Studio Code&quot;),<br>        (&quot;wingide&quot;, &quot;WingIDE&quot;)<br>    ]<br>).run()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*gC1COkR9yCiNu4GOrYtAFw.png" /></figure><h4>VIM clone</h4><p>I recommend you to visit their Gallery section on its website:</p><p><a href="https://python-prompt-toolkit.readthedocs.io/en/master/pages/gallery.html">Gallery - prompt_toolkit 3.0.30 documentation</a></p><p>You can find great demos, even a VIM clone!</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*DwvpYOtX3jl8sWmZWNFC3Q.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6e73d30891a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Auto-generating Regular expressions from a wordlists with Python]]></title>
            <link>https://cr0hn.medium.com/auto-generating-regular-expressions-from-a-wordlists-with-python-d15330df6295?source=rss-e88f464b9d9c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d15330df6295</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[wordlist]]></category>
            <category><![CDATA[trie]]></category>
            <category><![CDATA[regex]]></category>
            <dc:creator><![CDATA[Daniel Alfocea]]></dc:creator>
            <pubDate>Fri, 12 Aug 2022 13:19:47 GMT</pubDate>
            <atom:updated>2022-08-20T13:45:50.709Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*r09GpGpKoNyHfWuTsYW0Mw.jpeg" /></figure><p>Making regular expressions (REGEX) is sometimes an arduous task.</p><p>If we need to create a REGEX that matches a set of words, we need to analyse them and include all the necessary conditions to match them.</p><p>It’s very common in Web Apps, filters, or something else that has to match if a word matches with a set of allowed words.</p><p>Let’s say you want to detect lousy language. You can write something like:</p><pre>import re<br><br>bad_words_regex = re.compile(r&#39;&#39;&#39;([bB][aA][sS][tT][aA][rR][dD]|[fF][uU][cC][kK])&#39;&#39;&#39;)<br>word = input(&quot;Enter your word&quot;)<br><br>if bad_words_regex.match(word) is not None:<br>	print(&quot;Moderate your language!&quot;)<br>else:<br>	print(&quot;Good boy&quot;)</pre><p>Writing REGEX for a small wordlist is ok, but it is not manageable for an large set of words.</p><p>Trieregex is a project that automatically uses a Trie to generate complex REGEX from a set of words.</p><pre>import re<br><br>from trieregex import TrieRegEx as TRE<br><br>words = [&#39;bastard&#39;, &#39;fuck&#39;, &#39;losser&#39;]<br><br># Add word(s)<br>tre = TRE(*words)  # word(s) can be added upon instance<br><br># Create regex pattern from the trie<br>regex_pattern = tre.regex()<br><br># Add boundary context and compile for matching<br>bad_words_regex = re.compile(f&#39;\\b{regex_pattern}\\b&#39;)<br><br>word = input(&quot;Enter your word&quot;)<br><br>if bad_words_regex.match(word) is not None:<br>	print(&quot;Moderate your language!&quot;)<br>else:<br>	print(&quot;Good boy&quot;)</pre><p><strong>Referencies</strong></p><ul><li>Trieregex: <a href="https://github.com/ermanh/trieregex">https://github.com/ermanh/trieregex</a></li><li>Trie: <a href="https://en.wikipedia.org/wiki/Trie">https://en.wikipedia.org/wiki/Trie</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d15330df6295" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>