<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://gdickmann.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://gdickmann.github.io/" rel="alternate" type="text/html" /><updated>2025-09-23T19:14:04+00:00</updated><id>https://gdickmann.github.io/feed.xml</id><title type="html">The back page of the internet</title><subtitle>Simply putting my thoughts on the internet where people can&apos;t reach that much.</subtitle><author><name>Gustavo Henrique Dickmann</name></author><entry><title type="html">Dipping toes in AOT compilation</title><link href="https://gdickmann.github.io/2025/09/23/aot-compilation.html" rel="alternate" type="text/html" title="Dipping toes in AOT compilation" /><published>2025-09-23T00:00:00+00:00</published><updated>2025-09-23T00:00:00+00:00</updated><id>https://gdickmann.github.io/2025/09/23/aot-compilation</id><content type="html" xml:base="https://gdickmann.github.io/2025/09/23/aot-compilation.html"><![CDATA[<p>In Brazil we have a developer bubble on Twitter and people like to interact in there. One day, a guy created a back-end challenge and asked people to join the fun. A couple of editions happened already and in the last one I played around with multiple .NET solutions; AOT compilation was a common thing to see!</p>

<p>If you dip your toes in AOT compilation you’ll have to be familiar with some concepts before.</p>

<h2 id="managed-and-unmanaged-code">Managed and unmanaged code</h2>

<p>The .NET framework has multiple technologies (ASP.NET for web, WinForms for desktop, EF for ORM), including the Common Language Runtime, usually abbreviated to CLR - the .NET runtime.</p>

<p>A runtime, which is a programming language and framework agnostic term, it’s the environment responsible for <em>basically</em> executing your high-level code into low-level code (along with other features like memory management, type checking and exception handling). When writing C#, you won’t have to worry about memory allocation/deallocation, stack management, type safety, etc… however, these concepts still exist, and they’re managed by the runtime! This is called managed code.</p>

<p>When writing C/C++, you’ll have to worry about pretty much everything related to management - it’s an unmanaged code. The program compilation is just a binary that the OS loads into memory and starts.</p>

<p>This is the whole beauty of managed code. Instead of writing in beep-boop…</p>

<p><img src="/images/2025-09-23-aot-compilation/assembly.jpg" alt="ugh" /></p>

<p>…you’ll write a little more in <em>human</em>.</p>

<p>At the end of the day, the runtime it’s simply (but not a simple) an engine that abstracts these managements that, when made manually, would commonly <a href="https://www.welcometothejungle.com/en/articles/btc-ariane-5-bug-software">result in crashes</a>. That’s why low-level languages have little, if any runtime.</p>

<h2 id="intermediate-language">Intermediate Language</h2>

<p>One of the many .NET framework technologies are programming languages. Today, we have 3 of them: the popular and cool C#, F# and Visual Basic (old and uncool).</p>

<p>As every high-level language, they need to be translated into machine code. Instead of translating each of these high-level languages into binary code directly, each programming language compiler (note: not the runtime) translates the high-level code into an abstraction layer called <em>Intermediate Language</em> (IL) or sometimes called <em>Common Intermediate Language</em> (CIL).</p>

<p><img src="/images/2025-09-23-aot-compilation/high-level-to-il.png" alt="High-level to machine code using CLR" /></p>

<p>The compiler of C#, for instance, can usually be found at <code>C:\Windows\Microsoft.NET\Framework64\[version]\csc.exe</code>.</p>

<p>This abstraction layer makes the runtime programming language agnostic. The only runtime domain is the Intermediate Language, independently from which language it was originally compiled.</p>

<p>Since the Intermediate Language it’s the only language to be translated into native code, there’s no need for each programming language compiler to adapt its source code for specific CPU architectures - the CLR does that job with the abstraction layer, the Intermediate Language.</p>

<h2 id="now-whats-aot-compilation">Now, what’s AOT compilation?</h2>

<p>AOT means Ahead-of-Time compilation and it is one of the multiple compilation strategies there are - each one of them having its own advantages and disadvantages.</p>

<p>When you publish a .NET Web API without any explicit compilation strategy, for instance, .NET will compile your application as Just-In-Time compilation, aka “JIT” compilation. That’s the default compilation strategy for most (if not all) .NET applications.</p>

<pre><code class="language-bash"> dotnet publish -c Release -o /publish
</code></pre>

<p>In JIT compilation, the IL (or the JVM bytecode in Java) is translated into machine code at runtime - that means each chunk of IL code will be translated only when it is actually reached (note: JIT compilation will always use an intermediate language to translate it to machine code. If it would use a high-level language directly - like AOT does (we will get there) -, the cost of speed would be much higher because these intermediate languages will always be lower level).</p>

<p>Thus, high-level languages compilers such as the csc.exe will translate high-level code to Intermediate Language, a lower-level version of the code that makes it easier to translate it to machine code. Translating the IL to machine code is now the runtime role, not the compiler role. At runtime, you choose which compilation strategy you want for translating IL to machine code.</p>

<p>Important to remember that there are multiple CPU architectures out there and any set of instructions that you need to execute must be adapted for the CPU architecture the code it’s going to run. In .NET, this adaption is made in the runtime. That’s why you can run IL code in any CPU architecture since the host has the .NET runtime configured.</p>

<p>Now if JIT compiles bytecode into machine code on demand and uses the runtime to adapt the machine code for specific CPU architectures, AOT does it in a different way: like the name itself suggests, the compilation process is made ahead of time, which is during build-time rather than during run-time. That means IL is translated into machine code when you build your project for the first time. Thus, you must specify the CPU architecture up front, because the produced binary already contains instructions for that target (the app it’s mostly self-contained and does not require a JIT compiler at runtime now):</p>

<pre><code class="language-bash"> dotnet publish -r win-x64 -c Release
</code></pre>

<h2 id="aot-compilation-in-net">AOT compilation in .NET</h2>

<p>To build a .NET application using AOT, you’ll first have to enable it in the project file</p>

<pre><code class="language-xml">&lt;PropertyGroup&gt;
    &lt;PublishAot&gt;true&lt;/PublishAot&gt;
&lt;/PropertyGroup&gt;
</code></pre>

<p>and then build it with the specified CPU architecture as already shown above:</p>

<pre><code class="language-bash"> dotnet publish -r win-x64 -c Release
</code></pre>

<p>When you build your application using AOT, .NET produces it as a self-contained app. <a href="https://learn.microsoft.com/en-us/dotnet/core/deploying/?pivots=visualstudio#self-contained-deployment:~:text=to%20use.-,Advantages,-Control%20.NET%20version">Here, you can read some advantages and disadvantages about it</a> and <a href="https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/?tabs=windows%2Cnet8#:~:text=%3C/PropertyGroup%3E-,Limitations%20of%20Native%20AOT%20deployment,-Native%20AOT%20apps">its limitations</a> too.</p>

<h2 id="conclusion">Conclusion</h2>

<p>As <em>most</em> things in computer science, each compilation strategy brings it’s own pros and cons. IMO you’d usually not worry about these things unless you’re working in a high-performance focused application - which was the case of the back-end challenge I mentioned!</p>

<p>I’d compare benchmarks between both compilation strategies but now I have a Defect to work on and a manager to please!</p>]]></content><author><name>Gustavo Henrique Dickmann</name></author><category term="Other" /><summary type="html"><![CDATA[In Brazil we have a developer bubble on Twitter and people like to interact in there. One day, a guy created a back-end challenge and asked people to join the fun. A couple of editions happened already and in the last one I played around with multiple .NET solutions; AOT compilation was a common thing to see!]]></summary></entry><entry><title type="html">O uso de threads do BackgroundService no .NET Core</title><link href="https://gdickmann.github.io/2025/05/15/background-services-dotnet.html" rel="alternate" type="text/html" title="O uso de threads do BackgroundService no .NET Core" /><published>2025-05-15T00:00:00+00:00</published><updated>2025-05-15T00:00:00+00:00</updated><id>https://gdickmann.github.io/2025/05/15/background-services-dotnet</id><content type="html" xml:base="https://gdickmann.github.io/2025/05/15/background-services-dotnet.html"><![CDATA[<p>Recentemente precisei escrever um algoritmo onde uma classe herdada de <code>BackgroundService</code> - classe abstrata que implementa <code>IHostedService</code>, a interface que roda fluxos em segundo plano - rodava infinitamente. A regra de negócio era executada apenas 1 vez no mês, mas mesmo assim você precisa de uma thread para verificar se essa <em>é a vez do mês</em>.</p>

<pre><code class="language-csharp">class MyCustomWorker : BackgroundService
{
    private const int RunAt = 1;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            if (DateTime.UtcNow.Day == RunAt &amp;&amp; DateTime.UtcNow.Hour == RunAt)
            {
                await DoAsyncWork();
            }
        }
    }
}
</code></pre>

<p>Quando esse worker é injetado com <code>AddHostedService&lt;T&gt;</code>, qualquer outro worker injetado também com <code>AddHostedService&lt;T&gt;</code> não será mais executado - e isso se deve pela forma em que o runtime do .NET gerencia a inicialização desses workers.</p>

<p>Entender o motivo desse problema te força a entender um pouco mais sobre assincronicidade e sincronicidade, um conceito muito mais complexo do que se parece a primeira instância.</p>

<h2 id="threads">Threads</h2>

<p><em>Na ciência da computação, a thread é a menor sequência de instruções programadas que podem ser gerenciadas independentemente por um scheduler, que normalmente faz parte do sistema operacional.</em></p>

<p><img src="/images/2025-05-15-background-services-dotnet/thread.png" alt="alt text" /></p>

<p><em>Fonte: Wikipedia</em></p>

<p>Ou seja, dentro de cada thread há um fluxo de código que você define. Tudo o que roda por um programa de computador é executado por pelo menos uma thread (e várias delas podem ser executadas ao mesmo tempo).</p>

<p>Quando se é usado um <code>await Async()</code>, a thread é liberada para o thread-pool se <code>Async()</code> for I/O bound (ou seja, um processo que não precise de uma thread, como por exemplo esperar o resultado de um banco de dados ou de uma requisição HTTP).</p>

<p>Isso significa que, enquanto um fluxo que não está utilizando nenhuma thread é realizado (e eu preciso esperar o resultado dele), eu devolvo a thread que eu estava usando até então para o thread-pool - e lá algum processo pode utilizar essa thread para um processo CPU bound (ou seja, um processo que de fato precise de uma thread da CPU).</p>

<h2 id="inicialização-do-backgroundservice-pelo-runtime-do-net-core">Inicialização do BackgroundService pelo runtime do .NET Core</h2>

<pre><code class="language-csharp"> await AAsync();
 await BAsync();
 await CAsync();
</code></pre>

<p>Ao usar o <code>await</code>, o código é executado de forma sequencial, ou seja, <code>BAsync()</code> só será executado quando <code>AAsync()</code> for finalizado e <code>CAsync()</code> só será executado quando <code>BAsync()</code> for finalizado. O ganho, nesse caso, é você liberar a thread para o thread-pool para outros processos utilizá-lo enquanto você espera pela resposta de cada método.</p>

<p>Dito isso,</p>

<pre><code class="language-csharp">AAsync();
BAsync();
CAsync();
</code></pre>

<p>não usar o <code>await</code> executará <code>AAsync()</code>, <code>BAsync()</code> e <code>CAsync()</code> de forma assíncrona, mesmo que na definição desses métodos hajam operações <code>await</code>.</p>

<p>Mas <code>AAsync()</code> pode travar para sempre mesmo sem um <code>await</code> em sua chamada, e é exatamente isso que acontece com o <code>BackgroundService</code>.</p>

<p>Na <a href="https://github.com/dotnet/runtime/blob/e3ffd343ad5bd3a999cb9515f59e6e7a777b2c34/src/libraries/Microsoft.Extensions.Hosting.Abstractions/src/BackgroundService.cs#L37">definição do construtor do <code>StartyAsync()</code> do runtime do .NET</a>, o método <code>ExecuteAsync()</code> - que é o nosso worker - é chamado sem um <code>await</code>.</p>

<p>Como resultado, o runtime irá iniciar a execução do worker e, sem esperar pelo resultado dele, retornará um <code>Task.CompletedTask</code>, finalizando assim a execução de <code>StartAsync()</code>. Isso faz sentido, pois a ideia não é o runtime esperar pelo término de cada worker (afinal é um trabalho em segundo plano), mas sim apenas inicializá-los.</p>

<p>Agora, importante entender como o <code>StartAsync()</code> é chamado pelo runtime.</p>

<p>Na <a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-9.0&amp;tabs=visual-studio#:~:text=StartAsync%20should%20be%20limited%20to%20short%20running%20tasks%20because%20hosted%20services%20are%20run%20sequentially%2C%20and%20no%20further%20services%20are%20started%20until%20StartAsync%20runs%20to%20completion.">documentação da Microsoft</a>, é especificado que o <code>StartAsync()</code> é chamado de forma sequencial, ou seja, com o uso do <code>await</code>. Simplificando, o runtime faz o equivalente de:</p>

<pre><code class="language-csharp">await myCustomWorker.StartAsync();
await smsWorker.StartAsync(); 
await cleanRecordsWorker.StartAsync();
</code></pre>

<p>Dado a definição de <code>StartAsync()</code>, sabemos que o runtime vai apenas iniciar cada worker e, sem esperar por seu resultado, irá nos retornar o <code>Task.CompletedTask</code> - fazendo assim com que o <code>await myCustomWorker.StartAsync()</code> seja finalizado, depois <code>await smsWorker.StartAsync()</code> e depois <code>await cleanRecordsWorker.StartAsync()</code>, tudo de forma basicamente instantânea.</p>

<p>No entanto, se nossos workers não liberarem a thread instantaneamente (e a thread é liberada ao fazer o uso do <code>await</code>, como explicado), a linha</p>

<pre><code class="language-csharp">// Store the task we're executing
_executingTask = ExecuteAsync(_stoppingCts.Token);
</code></pre>

<p>do construtor de <code>StartAsync()</code> ficará travada esperando a liberação da thread. Ela está “esperando”, mas sem o <code>await</code>. A thread ainda não foi liberada para a continuação do fluxo do construtor (e como consequência os outros workers não são inicializados).</p>

<p>Na definição dada de <code>MyCustomWorker</code>, nenhum <code>await</code> é executado - logo, nenhuma thread é liberada e consequentemente a chamada de <code>ExecuteAsync()</code> irá travar. Com a chamada de <code>ExecuteAsync()</code> travada, o runtime não vai finalizar a execução de <code>await myCustomWorker.StartAsync()</code> (porque estamos esperando o término com o <code>await</code>) e nenhum outro worker será executado.</p>

<p>Esse design faz sentido pois se nenhum <code>await</code> é utilizado (e o <code>await</code> é utilizado para operações I/O bound), uma operação CPU bound está sendo executada - e como sabemos, uma operação CPU bound precisa de… threads de CPU.</p>

<p>Na prática, se o worker inicia com uma lógica síncrona que demora 10 segundos e só depois um <code>await</code> é executado, a chamada de <code>ExecuteAsync()</code> no construtor de <code>StartAsync()</code> só será liberada depois dos 10 segundos.</p>

<pre><code class="language-csharp">class MyCustomWorker : BackgroundService
{
    private const int RunAt = 1;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        MetodoCPUBoundQueDemora10Segundos(); // aqui o construtor tá travado (pois estamos usando threads)
        var dados = await BuscaDadosNoBancoAsync(); // aqui a thread é liberada e o construtor continua seu fluxo

        while (!stoppingToken.IsCancellationRequested)
        {
            if (DateTime.UtcNow.Day == RunAt &amp;&amp; DateTime.UtcNow.Hour == RunAt)
            {
                await DoAsyncWork();
            }
        }
    }
}
</code></pre>

<p>Um loop, como é o caso do <code>MyCustomWorker</code> na linha <code>while (!stoppingToken.IsCancellationRequested)</code>, também é uma operação CPU bound, ou seja, um worker que inicia com um looping também irá travar a chamada de <code>ExecuteAsync()</code> - mas dessa vez irá travar pra sempre!</p>

<h2 id="a-solução">A solução</h2>

<p>Se uma operação CPU bound é executada no início do nosso worker, não queremos que o runtime espere o término dessa operação. Ele pode continuar o seu fluxo e inicializar os outros workers e, depois, essa operação CPU bound arranja uma outra thread no thread-pool. Pra liberar a thread sem necessariamente <code>await</code>ar algo, basta usar <code>await Task.Yield()</code>:</p>

<pre><code class="language-csharp">class MyCustomWorker : BackgroundService
{
    private const int RunAt = 1;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await Task.Yield();

        while (!stoppingToken.IsCancellationRequested)
        {
            if (DateTime.UtcNow.Day == RunAt &amp;&amp; DateTime.UtcNow.Hour == RunAt)
            {
                await DoAsyncWork();
            }
        }
    }
}
</code></pre>

<p><code>await Task.Delay(1)</code> também funciona pelo fato de liberarmos a thread no <code>await</code>. <code>Task.Yield()</code> é a forma formal de se fazer isso.</p>

<p>Com isso, qualquer código lento ou qualquer loop não irá travar a execução de <code>ExecuteAsync()</code> e todos os outros workers serão inicializados corretamente.</p>]]></content><author><name>Gustavo Henrique Dickmann</name></author><category term="Other" /><summary type="html"><![CDATA[Recentemente precisei escrever um algoritmo onde uma classe herdada de BackgroundService - classe abstrata que implementa IHostedService, a interface que roda fluxos em segundo plano - rodava infinitamente. A regra de negócio era executada apenas 1 vez no mês, mas mesmo assim você precisa de uma thread para verificar se essa é a vez do mês.]]></summary></entry><entry><title type="html">Bananas are OP. Here’s why.</title><link href="https://gdickmann.github.io/2022/04/28/bananas-are-op.html" rel="alternate" type="text/html" title="Bananas are OP. Here’s why." /><published>2022-04-28T00:00:00+00:00</published><updated>2022-04-28T00:00:00+00:00</updated><id>https://gdickmann.github.io/2022/04/28/bananas-are-op</id><content type="html" xml:base="https://gdickmann.github.io/2022/04/28/bananas-are-op.html"><![CDATA[<p>I never was a fruit guy. To be honest, I remember eating fruits with more frequency when I was about ~ 10 years old. After that, I (not proudly) didn’t eat too much
fruits. And yeah, I mean <em>ANY</em> kind of fruit. Also, I mean any fruit at all. Not even a Banana (note that it’s ‘Banana’, not ‘banana’, because now I’m conviced that Bananas are a kind of divinity) - which I remembered yesterday how good it was.</p>

<h2 id="why-bananas-are-op">Why Bananas are OP.</h2>

<p>Yesterday I was hanging out with two friends of mine when I needed to eat something before college. I generally buy some junkie foods and don’t care at all, but these two friends are healthy and happy people. One of them suggested to buy two Bananas and an apple (note that it’s ‘apple’, not ‘Apple’, because apple isn’t a divinity for me - <em>not a diss for Apple, the company</em>). Of course that I laughed at them at first, but then I started to really take this idea into account. Was when I, for the first time after I don’t know how many years, went to buy a Banana. Now, a few things to consider.</p>

<h2 id="bananas-are-really-cheap">Bananas are really cheap.</h2>

<p>That was the first thing that I noticed when I bought them. 2 Bananas did cost 0,98 brazilian bucks! One of my friends also said that it was too expansive, but who cares? 0,98 for TWO beautiful and colorful Bananas. I took them. Then I bought the apple, that cost me 2,95 bucks. And that’s it, everything worked fine.</p>

<h2 id="bananas-design-are-genius">Bananas design are genius.</h2>

<p>Stop and think about it. A natural fruit have such a genius design. You look at a Banana and you already know how it works, you know what you’re supposed to do.</p>

<p><img src="/images/2022-04-28-bananas-are-op/banana.png" alt="alt text" /></p>

<p>First, the Banana peel protect the fruit. Besides protecting it, the peel contains NUTRIENTS!!! There is literally no downside - at least as far as I know. I never ate the peel and I don’t know if I want to, but just the fact that Banana’s shield contains nutrients is an incredible thing.
Second, the shape of a peeled Banana is satisfying to look at. When you’re eating something beautiful, you naturally want more of that food. That’s the case of Bananas.</p>

<p><img src="/images/2022-04-28-bananas-are-op/peeled_banana.png" alt="alt text" /></p>

<h2 id="bananas-are-tasty">Bananas are tasty</h2>

<p>Genuine question: Is there someone in this life that doesn’t like Bananas taste? Someone that says: “Oh, well, I don’t like the sweet of Bananas. I prefer Apples!”. Honestly, I don’t think so. Bananas taste are just incredible, everything is balanced. That means that you can eat something healthy and that is tasty. Again, another incredible point from Bananas.</p>

<h2 id="bananas-can-be-used-as-fertilizer">Bananas can be used as fertilizer</h2>

<p>Simply amazing. Can you understand that? You eat the Banana but you still got the peel. You don’t need to necessarily throw it away in a trash, you can just throw it around plants. There are better ways to use Banana peel as fertilizer, but this will not harm the environment. +10 points for Bananas.</p>

<h2 id="banana-is-synonymous-of-chimpanzees-the-smarter-animal-before-us">Banana is synonymous of chimpanzees, the smarter animal before us.</h2>

<p>Some haters may say that we “think that chimpanzees eat Bananas” because they are grown in tropical areas, where chimpanzees usually live. You can believe in that if you have an average IQ, but if you think more about it, you realize that chimpanzees eat Bananas (and are their preferred fruit) because they know everything that you’re reading. They know how OP Bananas are and know that they get advantage eating a fruit like that.</p>

<p>Why do you think that hippos aren’t smart as chimpanzees? The only accepted answer is because they don’t eat Bananas as chimpanzees do. Simple like that.</p>

<h2 id="bananas-are-healthy">Bananas are healthy</h2>

<p>Last but not least, Bananas are very healthy. It has high levels of potassium, which helps regulate water levels in the body. It is rich in vitamins, namely A, C, E and the B complex. It also has essential minerals such as calcium, zinc, magnesium, and more. How can something be good and healthy? OP.</p>

<h2 id="conclusion">Conclusion</h2>

<p>Bananas are a kind of God-fruit. They have beautiful design, are tasty and healthy. I’m not trying to convice you to eat Bananas and being healthy, I’m just saying facts.</p>]]></content><author><name>Gustavo Henrique Dickmann</name></author><category term="Other" /><summary type="html"><![CDATA[I never was a fruit guy. To be honest, I remember eating fruits with more frequency when I was about ~ 10 years old. After that, I (not proudly) didn’t eat too much fruits. And yeah, I mean ANY kind of fruit. Also, I mean any fruit at all. Not even a Banana (note that it’s ‘Banana’, not ‘banana’, because now I’m conviced that Bananas are a kind of divinity) - which I remembered yesterday how good it was.]]></summary></entry><entry><title type="html">ELI5: how does Blockchain allow a system to be decentralized?</title><link href="https://gdickmann.github.io/2022/04/04/blockchain-decentralized-system.html" rel="alternate" type="text/html" title="ELI5: how does Blockchain allow a system to be decentralized?" /><published>2022-04-04T00:00:00+00:00</published><updated>2022-04-04T00:00:00+00:00</updated><id>https://gdickmann.github.io/2022/04/04/blockchain-decentralized-system</id><content type="html" xml:base="https://gdickmann.github.io/2022/04/04/blockchain-decentralized-system.html"><![CDATA[<h3 id="what-are-centralized-and-decentralized-services">What are centralized and decentralized services?</h3>

<p>When we talk about decentralization the first thing we correlate is the currency that has been in hype for years: Bitcoin. Bitcoin is a virtual, decentralized currency that is distributed and stored on the Blockchain - the technology that enables decentralization.</p>

<p>A decentralized system is one that does not have a central entity/authority acting as an intermediary. The Brazilian Real, for example, is a centralized currency: the Brazilian Mint acts as the central authority and intermediary; it defines how many banknotes and coins will be made. They are the ones in total control of the currency.</p>

<p>Bitcoin has a finite number of copies and all its transactions are public and unchangeable. Because the network is run by several users (the miners), this makes it decentralized.</p>

<p>The theory of a decentralized monetary system is simple, as you can see. We can simply think of a currency that has all its transactions public, has no authorities acting as intermediaries, and somehow cannot have its transaction history changed. Before the invention of the Blockchain (which came along with the invention of Bitcoin, by Satoshi Nakamoto) we never had the ability to implement such a system in a technical way, that is, implementing and popularizing it was always the problem.</p>

<h3 id="why-create-a-decentralized-monetary-system">Why create a decentralized monetary system?</h3>

<p>Bitcoin was created by Satoshi Nakamoto (a pseudonym, since nobody knows his real identity) who, we all believe, did not support the idea of banks having access to all our transactions. Knowing this, the fact that we have a monetary system where there are no bank interventions is a remarkable advantage. Consequently, we have a decrease in fraud and/or manipulation.</p>

<p>A decentralized system, however, is commonly used for crimes. Since there is no one acting as an intermediary, remaining anonymous within the network is extremely simple; this is why criminals demand cryptocurrencies as a form of payment in most cases.</p>

<p>As a consequence of the anonymity, money laundering with cryptocurrencies has been used many times.</p>

<h3 id="decentralized-system-in-practice">Decentralized system in practice</h3>

<p>Imagine that you, me, and Joãozinho want to create a system similar to Bitcoin. All the monetary transactions we make with each other are stored on a sheet of paper. At the end of each month, we pay what we owe each other.</p>

<p><img src="/images/2022-04-04-blockchain-decentralized-system/transaction.png" alt="alt text" /></p>

<p>This is, in a nutshell, how a Blockchain works with cryptocurrencies: It stores all transactions in public form. If we were all honest, this system would work perfectly: nobody would change the value of the transactions, the sender or the receiver of the transactions. But in this paper scenario, nothing prevents someone from taking a pen and adding a few extra zeros to Joãozinho’s transaction.</p>

<p><img src="/images/2022-04-04-blockchain-decentralized-system/transaction-02.png" alt="alt text" /></p>

<p>Two things prevent the data in a Blockchain from being altered: its architecture, which will be commented on, and mining.</p>

<h3 id="cryptocurrency-mining">Cryptocurrency Mining</h3>
<p>All transactions on a Blockchain need to be validated. This means that if Bob transfers 1 BTC to Alice, the amount will not automatically be transferred to his wallet, because first it needs to be validated. The act of validating a transaction is what we call mining.</p>

<p>Cryptocurrency mining is done by miners. Miners are nothing more than users who place their computing power (hardware) on the Blockchain network. The more computing power, the faster the transactions will be validated.</p>

<p>Validating a transaction is validating a purposefully complex mathematical calculation (in the case of the Proof of Work validation method - protocol used by Bitcoin). Miners solve mathematical calculations that purposefully require a lot of computing power. This process, depending on the Blockchain, can take seconds, minutes, or even hours. When this mathematical calculation is completed by a miner, a new block in the chain (the data of a transaction) will be added and the miner will be rewarded for his computational effort. Only at that point will a transaction be completed.</p>

<p>In other words, the role of miners is simply to put their computing power to solve mathematical calculations. When these calculations are solved, the block is validated and can be added to the chain.</p>

<p>The purpose of these calculations being purposely complex is directly linked to the architecture of the Blockchain that must first be understood.</p>

<h3 id="technically-speaking-how-does-a-blockchain-allow-a-system-to-be-decentralized">Technically speaking, how does a Blockchain allow a system to be decentralized?</h3>

<p>Imagine the Blockchain as the name implies: a chain of blocks connected by a chain.</p>

<p>Its architecture consists of “blocks” that have the reference of the previous block (chain) - like an interconnected chain - and each block has a stored information (a monetary transaction, for example). Having a reference to the previous block is what makes the Blockchain immutable, i.e., almost impossible to have its information changed.</p>

<p><img src="/images/2022-04-04-blockchain-decentralized-system/blockchain.png" alt="alt text" /></p>

<p>Each block contains the following information:</p>

<ul>
  <li>
    <p>Amount: the amount of Bitcoins to be transferred;</p>
  </li>
  <li>
    <p>Sender: the hash of the block that is sending the Bitcoins (sender);</p>
  </li>
  <li>
    <p>Recipient: the hash of the block that is receiving the Bitcoins;</p>
  </li>
  <li>
    <p>Hash: the hash of the current block;</p>
  </li>
  <li>
    <p>Previous hash: the hash of the previous block.</p>
  </li>
</ul>

<p>The first block (Block 1) is called the genesis block. As you can see, it has one less property: the previous hash. This is because this is the first record in the Blockchain, i.e., there is no previous block to store the hash. It is important to remember that the hash of each block is defined by the information it contains. If a piece of information changes, the hash of the block will automatically change as well.</p>

<p>The picture gives an example of a Blockchain with three transactions recorded. The first transaction was 10 Bitcoins for address 345, the second was 1 Bitcoin for address 678, and the last transaction was 20 Bitcoins for address 91011.</p>

<p>Now imagine that someone modifies the properties of Block 1. Instead of 10 Bitcoins sent to hash 345, 20 Bitcoins are reported in the record. Unlike the sheet of paper example, this would cause problems due to the previous hash property that all blocks - with the exception of the genesis block - have.</p>

<p>Since one value of Block 1 (amount) has changed (from 10 to 20), the hash of the block will automatically change (from 123 - its original value). When the hash of this block changes, the previous hash property of the next block will also change. If this property changes, the original hash of this block will also change, and so on, causing a domino effect throughout the Blockchain. Automatically, the value of all blocks in the chain will change, and consequently, will have to be validated again.</p>

<h3 id="role-of-the-miners">Role of the miners</h3>

<p>Since all the blocks in the chain will change if a single value is modified, the entire chain will have to be validated again. As already mentioned, mining a single block in a chain can be a very time consuming task.</p>

<p>By default, the blockchain that will be considered true will be the one with the most blocks validated. Because of this, you would not be able to change the values of the records by yourself because you would need to validate all the blocks in the Blockchain again. Doing this successfully means having more computing power than all the miners in the entire world - something that is unlikely. In 2022, there are about 1,000,000 Bitcoin miners around the world. They all work non-stop to validate new blocks on the network. Since they all work around the clock validating blocks in a single chain, being able to change records and validate more blocks than they do is unlikely because you are at a computational power disadvantage.</p>

<p>The only possible way to successfully change the values of a blockchain is to validate more blocks than all 1,000,000 miners combined - which is physically almost impossible, since you would need to have a computational power as high as all the computational power of all the miners working in the chain.</p>

<p>In other words, the more miners working to validate blocks in the chain, the more computational power is required for a single person to change the records.</p>

<p>This is a very interesting approach because successfully changing records depends on something physical (hardware), not digital.</p>

<h3 id="the-only-way-to-change-the-records-of-a-blockchain---51-attack">The only way to change the records of a Blockchain - 51% Attack</h3>

<p>51% Attack is a type of attack where one person or a group of people have more computing power (51% +) than the power of all the miners together working on the chain. In this scenario, the individual could change one value in the chain and validate the entire chain again. Since he has a higher computational power than all the other miners combined, he could continue validating the chain and consequently validate more blocks; which would make the chain the largest in the blockchain. If this happened, it would be considered the true chain even though it contains changed data.</p>

<p>This means that you could only successfully alter the records of a blockchain if you mastered at least 51% of the computing power working on the chain.</p>

<h3 id="energy-consumption-for-transaction-validation">Energy consumption for transaction validation</h3>

<p>In May 2021, Elon Musk - one of today’s biggest cryptocurrency influencers - tweeted about Tesla, his electric vehicle company, no longer accepting Bitcoin as a form of payment.</p>

<p><img src="/images/2022-04-04-blockchain-decentralized-system/dk13xl5ejry61.png" alt="alt text" /></p>

<p>According to him, the rapid growth in the use of fossil fuels for mining the cryptocurrency worries him.</p>

<p>Bitcoin started to have a lot of visibility a few years ago, which made many people enter the mining market. Consequently, the demand for power and GPUs have increased dramatically, which directly influences their markets.</p>

<p><img src="/images/2022-04-04-blockchain-decentralized-system/15843.jpeg" alt="alt text" /></p>

<p>It is estimated that to validate a single Bitcoin transaction, about 2100 kWh of energy is used, which is roughly what an average American household consumes in 75 days.</p>

<p>All the rising energy prices have caused miners to opt for cheaper alternatives for mining, such as the fossil fuel that was commented on by Elon Musk. Because of the competition, miners are looking for cheaper options, but they are the most polluting, thus directly affecting the environment.</p>

<p>As a solution to this problem, new validation mechanisms are already being developed and even used, as is the case of Proof-of-Stake, a mechanism that will be used by the Ethereum network and that does not depend on computing power for validations.</p>

<h3 id="references">References</h3>

<ul>
  <li>https://pt.wikipedia.org/wiki/Blockchain</li>
  <li>https://ethereum.org/en/defi/</li>
  <li>https://ethereum.org/en/developers/docs/consensus-mechanisms/pos/</li>
  <li>https://bitcoin.org/bitcoin.pdf</li>
  <li>https://ethereum.org/669c9e2e2027310b6b3cdce6e1c52962/Ethereum_White_Paper_-_Buterin_2014.pdf</li>
</ul>]]></content><author><name>Gustavo Henrique Dickmann</name></author><category term="Other" /><summary type="html"><![CDATA[What are centralized and decentralized services?]]></summary></entry><entry><title type="html">“Why I created this blog” first post.</title><link href="https://gdickmann.github.io/2022/03/21/first-post.html" rel="alternate" type="text/html" title="“Why I created this blog” first post." /><published>2022-03-21T00:00:00+00:00</published><updated>2022-03-21T00:00:00+00:00</updated><id>https://gdickmann.github.io/2022/03/21/first-post</id><content type="html" xml:base="https://gdickmann.github.io/2022/03/21/first-post.html"><![CDATA[<p>At first, I wanted to create my own blog from the scratch. I opened my terminal, executed a new React application and gave up when I looked at the framework icon. I thought about how many front-end related things I would have to write and just closed everything.</p>

<p>But now I’m using this template that does everything that I need: write about random things that comes to my mind.</p>

<p>I’m creating this blog because I want to leave my thoughts on some topics on the internet. I also like to talk about my personal projects.</p>

<p>As I’m still not a influencer with 1kk followers, I won’t be an active poster. For now, I’m just doing it for fun and because I like the way I explain things. I think I’m good at it.</p>]]></content><author><name>Gustavo Henrique Dickmann</name></author><category term="Other" /><summary type="html"><![CDATA[At first, I wanted to create my own blog from the scratch. I opened my terminal, executed a new React application and gave up when I looked at the framework icon. I thought about how many front-end related things I would have to write and just closed everything.]]></summary></entry></feed>