<?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 Rafael Sarres de Almeida on Medium]]></title>
        <description><![CDATA[Stories by Rafael Sarres de Almeida on Medium]]></description>
        <link>https://medium.com/@rsarres?source=rss-3623df8da039------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*flOn3cxfVSgS9BEFGpyQbw.jpeg</url>
            <title>Stories by Rafael Sarres de Almeida on Medium</title>
            <link>https://medium.com/@rsarres?source=rss-3623df8da039------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 08:02:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rsarres/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[Wireshark´s finest hour]]></title>
            <link>https://rsarres.medium.com/wireshark-s-finest-hour-8e969ca0d29?source=rss-3623df8da039------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e969ca0d29</guid>
            <category><![CDATA[mwc-work]]></category>
            <dc:creator><![CDATA[Rafael Sarres de Almeida]]></dc:creator>
            <pubDate>Fri, 30 Jul 2021 22:56:35 GMT</pubDate>
            <atom:updated>2021-07-30T22:59:00.269Z</atom:updated>
            <content:encoded><![CDATA[<p>Long before DevOps revolution, traditional software development and infrastructure management teams shared an antagonistic relationship. In plain words, they used to fight like cats and dogs. This is a true story from my experience on one of these quasi-aggressive interactions.</p><p>From 2000 to 2008, I was part of the infrastructure team at Superior Court of Justice (STJ), one of Brazil´s highest justice courts. Besides taking care of the network, one of my responsabilities was to provide and support Tomcat application servers, the workhorses that pulled Java programs wagons for STJ´s intranet.</p><p>STJ software developers didn´t have any contraints on the production at the time, they could deploy a new application or update an existing one at anytime. Yes, I know: “Big mistake, Rafael”. But, give me a break, it was a long time ago, when Information Technology in STJ was, in reality, improvised. Our “servers” were just overglorified desktops spread across two rows of stands.</p><p>I was no java developer. I have developed in C++ and Pascal a lot during my university years and kept creating shell and perl scripts to support my role at STJ. On the other hand, I had developed great skills on application troubleshooting at network level using a packet sniffer, Sniffer Pro at first and, later, <strong>Wireshark</strong>. When I had spare time, I used to mirror busy server ports and I loved spending hours understanding the cascade of Ethernet frames.</p><p>I felt like Cypher staring at the <a href="https://en.wikipedia.org/wiki/Nebuchadnezzar_(The_Matrix)"><strong>Nebuchadnezzar</strong></a>´s Matrix console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/0*JjorowxZ0dyEY4I4" /><figcaption><em>“You get used to it, though. Your brain does the translating. I don’t even see the code. All I see is blonde, brunette, redhead.”</em></figcaption></figure><p>Unfortunately I didn´t see the beautiful women that Cypher describes, but I knew the traffic baseline as no one. It was long before this cryptography-everywhere era. HTTPS was an unnecessary burden to our deskt… err, servers. Bottom line, I could see <strong>everything: </strong>requests, responses, database queries, measure response times and correlate them.</p><p>Modesty aside, I was good. I was so good that other IT departments lined at my door for a troubleshooting analysis when things got rough. Database queries, authentication protocols, file server communication; I debugged them all. They came with the the well known symptoms: My application is slow, it fails at random times, and the most common:</p><p><em>“- I tested it thoroughly at my local development environment (application, files and database at a local desktop) and it worked fine everytime, now that I moved to production, my performance is crap. </em><strong><em>Your network sucks!</em></strong><em>”</em></p><p>9 out of 10 times I could pinpoint the bottleneck: Chattiness, huge file accesses or even some left out code that queried non-existent servers until a timeout. After some time they all learned to stop blaming my top-notch network and just came asking for help, which I gladly provided every time.</p><p>STJ had even given me a bonus for teaching a network troubleshooting course for other network administrators, where I taught every trick I had on my sleeve: packet filtering, reordering, time anchoring, tcp stream following, windowing, data reconstruction, HTTP request-database query correlation… Everything. Unfortunately, no other employee had reached my troubleshooting skill level.</p><p><strong>The network was my kingdom and I was the king.</strong></p><p>Enough blowing my own trumpet, let´s move on with the story. It was just another day at work when, suddenly, one of my Tomcat server crashes. First response: restart the service. The server runs fine again.</p><p>A couple of days later, another inexplicable crash in the middle of the afternoon. My boss complains. I ask the java developer team if they had made any change to the application recently. They say the code is months old and no change had been made.</p><p>Some days later, another crash. I had enough. Our users are complaining, my boss is blaming my servers and the java developers swear that they did not change anything. I put down my coffe mug, open my server console and get down to business. <strong>Time to get my hands dirty.</strong></p><p>I enable every java management extension I could find and start logging. Now I am just looking forward to the next crash, which, of course, happens soon enough.</p><p>I go through the logs, and what I found was a quick surge on the memory usage of the java process. It suddenly spiked to the maximum heap size and crashed the server, jumping from a healthy 50% to 100% in a matter of minutes. <strong>Memory leak, one of my favorites bugs.</strong> However, I still had no clue of what application or class had misbehaved.</p><p>I politely ask the developers once again: negative responses and some frowns upon me. Now I am pissed, but I did not say anything. Without the digital smoking gun, I cannot bring the case to court. Not yet, my boy. Not yet…</p><p>Out of management extensions left, I decided to call in the big guns on this case:</p><p><strong>RELEASE THE KRAKEN!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*8uKLEZsAF4UsqrXl" /><figcaption>It is nice to see you too, my baby.</figcaption></figure><ul><li>Wireshark laptop deploy: Check!</li><li>Server port mirror: Check!</li><li>Promiscuous mode: Check!</li><li>Spurious traffic filters: Check!</li><li>Circular buffers: Check!</li></ul><p>As the dusty fan of my beaten laptop starts roaring, an involuntary sneer appears on my face. I just have to wait for the incident to happen again, and it surely happens. But this time, the Shark has caught something. A phrase slips between my teeth:</p><p><strong>“Let´s get down to business, shall we…”</strong></p><p>I look at the java management extension logs and server port usage to pinpoint the approximate time the server started misbehaving. My clues led me to the exact time when the first wheel of the wagon had fallen off: <strong>12:45h PM!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*dROFtKrni5-A9g28" /><figcaption><strong><em>Clue 1</em></strong><em>: Abnormal data traffic increase minutes before each crash (I had two on this day)</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*7vCg_I-RAmK1vvUi" /><figcaption><strong>Clue 2</strong>: JVMStat Old Generation memory pool usage during the same time frame</figcaption></figure><p>I deep dive on the packets of that approximate time, and to my dismay, there are zillions of packets. I saw blondes, brunettes, redheads, dwarfs, zebras, giants, E.T.s…. But not a single defective request. The server was on a very busy time, the catch was simply too big to digest. It was a needle in a haystack. I had two clues, but no smoking gun. Yet.</p><p>Think, McFly, <strong>think! </strong>How is a misbehaving request different from a well behaved one?</p><p><strong>OF COURSE!!! There is no spoon!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*smf6DW0DzoXvww6-" /><figcaption><strong>The Oracle was right: there is no RESPONSE from a defective application!!!</strong></figcaption></figure><p>I crack my knuckles and start coding some filters. First, only HTTP requests. Then, I add the responses. I separate the individual streams, fiddle with the time counting and ordering and <strong>VOILA</strong>! I locate the <strong>third clue</strong>: the only HTTP request with absolutely no response. Just a TCP ack and radio silence. And it occurs minutes before the crash, right on the start of the memory usage climbing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*9ArzvaM9VMbETFlK" /><figcaption><strong>Clue 3</strong>: A HTTP request without an answer buried deep in a 74 seconds capture file with 100.000 packets, <em>aka</em>, a needle in a haystack</figcaption></figure><p>Now I remove some filters and analyze what packets appear around this problem. Surely enough, I found the <strong>fourth clue</strong>: a database query immediately after the reponseless HTTP request. And another. And another. The misbehaving request caused an infinite loop of repeating database queries, slowly crushing my poor server´s memory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*B7j2Ic1BDzysbgbc" /><figcaption><strong>Clue 4</strong>: A barrage of identical SQL queries just after the never answered HTTP request:</figcaption></figure><p>My last clue lead me to the depths of the java code. I extracted the offending SQL request text from the repeating packets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*ILFUMpcQ7qXqwrl8" /><figcaption>Clue 5: The fingerprint of the murderer</figcaption></figure><p>Now I had all the clues I needed to solve this mystery. It is time to locate the faulty code. I run a grep on my server files searching for the SQL query I had just discovered. I found the java file containing the query, and of course, it is inside a loop.</p><p><strong>The proverbial smoking gun full of developers fingerprints was right in front of my eyes!</strong></p><p>I march to the java developers office, kick the door in and, without warning, yell only the name of the defective java file. A guy on the corner of the office stares at me with big startled eyes and, in an almost inaudible squeak, moans:</p><p><em>“- This change shouldn´t have caused a problem…”</em></p><p>Long story short: Developers were kicked out of production servers. They now had to open a formal request to update applications outside of business hours. We have started a long due IT governance project.</p><p><strong>Epilogue</strong></p><p>In 2008, two months after I left STJ, I received a call from the new network administrator asking for help debugging an application misbehavior. I instructed him to mirror the correct server port, to capture some data during the issue and to send me the file.</p><p>Surely enough, I found the problem.</p><p>I recently heard that there are still tales around STJ about a legendary guy that used to roam around the building solving all kinds of IT problems with his unusual companion: a shark that lived in the network cables. The almighty…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/0*HfSyWOAobK29u55R.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e969ca0d29" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A segurança do PIX]]></title>
            <link>https://rsarres.medium.com/a-seguran%C3%A7a-do-pix-958c0fc9e015?source=rss-3623df8da039------2</link>
            <guid isPermaLink="false">https://medium.com/p/958c0fc9e015</guid>
            <category><![CDATA[segurança]]></category>
            <category><![CDATA[pix]]></category>
            <dc:creator><![CDATA[Rafael Sarres de Almeida]]></dc:creator>
            <pubDate>Fri, 20 Nov 2020 02:56:53 GMT</pubDate>
            <atom:updated>2020-12-01T23:29:32.243Z</atom:updated>
            <content:encoded><![CDATA[<p>O PIX é o novo sistema de transferência bancária instantânea criado pelo Banco Central do Brasil para permitir a movimentação de recursos entre contas bancárias ou de instituições de pagamento de forma simples, rápida e barata. Porém, a<a href="https://epocanegocios.globo.com/Economia/noticia/2020/09/epoca-negocios-ex-diretor-critica-velocidade-da-agenda-de-digitalizacao-do-bc-e-alerta-para-riscos.html">lguns depoimentos em veículos de notícias</a> e vídeos compartilhados via redes sociais tem questionado a segurança desse novo sistema.</p><p>Nesse artigo pretendo explicar o que é o PIX, apresentar seus diferenciais e avaliar a segurança do sistema em comparação aos métodos de transferência disponíveis anteriormente. Esse não é um artigo técnico que explica detalhes internos do sistema, mas foco especificamente na parte prática do PIX.</p><h3>Mas, afinal, o que é o PIX?</h3><p>O PIX é apenas mais uma forma de transferência bancária com algumas diferenças bem relevantes. Mas antes de explicar as diferenças, vamos falar sobre as características que o PIX <strong>compartilha</strong> com seus “irmãos”, a <strong>Transferência Eletrônica Disponível (TED)</strong>, <strong>Documento de Ordem de Crédito (DOC)</strong> e seu primo, o <strong>boleto bancário</strong>:</p><ul><li>Uma transferência PIX é uma movimentação de recursos entre contas bancárias ou de pagamentos de instituições do Sistema Financeiro Nacional.</li><li>Uma transferência PIX é <strong>irreversível</strong>, assim como TEDs, DOCs e boletos bancários.</li><li>Todas as modalidades de transferência bancária estão sujeitas a limites, e o PIX não é diferente. Nesse quesito, o Banco Central <a href="https://www.bcb.gov.br/estabilidadefinanceira/exibenormativo?tipo=Instru%C3%A7%C3%A3o%20Normativa%20BCB&amp;numero=40">editou norma específica</a> ancorando os limites das transações PIX aos limites de outras transações similares, como TEDs e compras no cartão de débito. Maiores detalhes, consulte a norma no link desse parágrafo.</li><li>Um cliente somente pode ordenar uma transferência PIX mediante apresentação das credenciais corretas para acesso a conta.</li></ul><p>Agora que apresentamos as similaridades, passemos para o que temos de novidades. O sistema PIX conta com algumas <strong>diferenças</strong> relevantes quando comparadas com TED e DOC. Elas são:</p><ul><li>O PIX funciona com o conceito de <strong>chaves</strong>. Uma chave é um destino para o valor que está sendo enviado, ele funciona como um “atalho” para as informações que normalmente temos que passar para receber o uma transferência eletrônica: Agência, conta, instituição e Cadastro de Pessoa Física (CPF). Com o PIX, é possível enviar recursos apenas as informações já usadas em uma TED, mas as chaves ajudam a tornar esse processo mais simples. Há diversos tipos de chaves, como e-mail, CPF, número de celular e até chaves aleatórias. O cadastro da chave é uma opção livre do cliente da instituição, você pode cadastrar uma chave para cada instituição com a qual mantém relacionamento, somente para algumas ou até não cadastrar nenhuma chave. <strong>É importante citar que não é necessário cadastrar a chave PIX para enviar ou receber recursos, ela apenas facilita o recebimento com uma informação mais simples.</strong></li><li>O sistema PIX possui <strong>suporte a QR Code</strong> padronizado. Alguns bancos já suportavam QR Codes para cobranças entre seus clientes, mas com o PIX, o serviço é universal e funciona em todos as instituições. Assim, é muito mais fácil passar sua chave PIX para o remetente do recurso. Segue um exemplo de QR Code abaixo de minha chave aleatória:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*snEL3Oq-jpKlRp6mkAmLng.png" /><figcaption>Exemplo de QR Code PIX</figcaption></figure><ul><li>A transferência <strong>leva apenas poucos segundos</strong>, diferente de minutos da TED e dias de um DOC. Por isso, ela é considerada instantânea, pois o valor é creditado na conta de destino praticamente na mesma hora de envio, independente de bancos envolvidos.</li><li>Uma transferência PIX pode ser realizada a qualquer momento, ela está <strong>disponível 24x7x365</strong>. Em comparação, TEDs somente podem ser feitas em dias úteis e em uma grade horária definida, normalmente entre 6:30h e 17:00h. Assim, o PIX se assemelha a transferências realizadas entre contas do mesmo banco e com os pagamentos realizados com o cartão de débito, pois ambas podem ser realizadas a qualquer dia e horário.</li><li>Transferências PIX funcionam <strong>entre quaisquer contas, mesmo entre contas de mesmo banco.</strong> Por isso, não é mais necessário perguntar se o destinatário possui conta em seu banco antes de se realizar uma transferência com o PIX. É só transferir que o sistema trata todos os detalhes internamente.</li><li>Enquanto TEDs e DOCs são tarifadas conforme a tabela de serviços de cada banco, transferências PIX são <strong>isentas de tarifas</strong> quando realizadas entre pessoas físicas e empreendedores individuais. Porém, há exceções na <a href="https://www.bcb.gov.br/estabilidadefinanceira/exibenormativo?tipo=Resolu%C3%A7%C3%A3o%20BCB&amp;numero=19">resolução do Banco Central do Brasil</a>. Por exemplo, a cobrança é permitida para pessoas jurídicas, quando for realizada o pagamento de um produto ou serviço. Algumas instituições financeiras já anunciaram gratuidade total para todas as transferências, assim, de forma geral, transferências PIX serão muito mais baratas do que as alternativas.</li><li>O sistema PIX permite <strong>cobranças com dados agregados</strong> como vencimento e juros, assim ele será uma alternativa aos boletos bancários com diversas vantagens. O principal avanço é a liquidação instantânea, pois boletos levam dias para serem compensados.</li></ul><p>Como podemos ver, o PIX trará facilidades e reduzirá custos na movimentação de valores no sistema financeiro nacional. Mas será ele seguro?</p><h3>A segurança do sistema PIX</h3><p>Como citado anteriormente, ninguém consegue iniciar uma transferência PIX a partir de uma conta sem apresentar as credenciais corretas para acessar sua conta, <strong>pois o PIX é apenas uma TED turbinada</strong>. Além disso, os limites de transferências são <strong>sempre iguais ou inferiores </strong>aos limites já aplicados a sua conta bancária para a realização de transferências como TED, DOC ou pagamento via cartão de débito. Logo, a premissa básica para um cliente ordenar uma transação PIX é a mesma para a realização de TEDs e ambas são irreversíveis.</p><p>Com base nessa premissa, não faz sentido <a href="https://epocanegocios.globo.com/Economia/noticia/2020/09/epoca-negocios-ex-diretor-critica-velocidade-da-agenda-de-digitalizacao-do-bc-e-alerta-para-riscos.html">achar que o PIX agora incentivará assaltantes a obrigar vítimas a realizar um PIX de todo seu dinheiro para o bandido</a>, pois, primeiro, <strong>há limites para as transferências PIX</strong>; e segundo, <strong>esse problema já existe hoje com a TED!</strong></p><p>Pessoalmente acho esse risco pequeno dada a dificuldade de um assaltante de rua criar contas em nomes de laranjas em instituições bancárias, pois certamente cada conta será encerrada pela instituição após cada assalto. Além disso, o meliante tem que sacar o dinheiro rapidamente após o roubo, uma vez que a instituição irá bloquear o valor assim que o caso for reportado.</p><p>Infelizmente esse risco não é inexistente, claro, principalmente em ações mais elaboradas de bandidos como sequestros. Mas o PIX não aumenta em nada esse problema, como a Dona Cleide nos explica muito bem no Twitter:</p><h3></h3><p>Sofri sequestro relâmpago em set, meus cartões foram pegos e sob a mira de uma arma na cabeça de meu marido, tive q passar senhas e aguardar até q eles tivessem feito tudo q achavam q deviam fazer. Qual a diferença em ser pix, pox, ou pux? O problema é a IMPUNIDADE.</p><p>Uma questão que tenho visto de forma repetida é : <em>“Se alguém descobrir minha chave, ele conseguirá retirar meu dinheiro da conta?”</em>. A resposta é um esplêndido <strong>NÃO</strong>! Sua chave é apenas o destino do dinheiro, assim como o endereço é o destino de uma carta. Ninguém consegue acessar sua conta sabendo apenas sua conta e agência, não é mesmo?</p><p>Adicionalmente, uma das chaves PIX é o seu número de celular, informação que não possui maior grau de sigilo. Assim, caso essa chave seja cadastrada por você, todas as pessoas que possuem essa informação em sua lista de contatos (amigos, familiares e conhecidos) podem te enviar dinheiro. Ficou muito mais simples receber recursos.</p><p>Outro comentário que sempre tenho ouvido é que <em>“as pessoas não devem cadastrar suas chaves PIX para ficar mais seguras”</em>. Não entendo a lógica desse argumento, uma vez que a chave serve única e exclusivamente para receber recursos de forma mais simples, não para autorizar transferência de recursos. <strong>Quando você deixa de cadastrar sua chave, você apenas está dificultando o envio de recursos para você via PIX, incentivando o pagamento de tarifas para realizar TEDs ou DOCs.</strong> Ou pior, você cria desculpas para que nunca te paguem as dívidas. <strong>Com ou sem chaves cadastradas, as contas estão estão habilitadas a enviar e receber transferências PIX, assim como TEDs e DOCs.</strong></p><p><em>“Ah, mas não quero compartilhar meu e-mail, meu número de celular ou meu CPF!”</em> Ok, então você pode cadastrar uma chave aleatória, um monte de números e letras que não tem nenhuma relação com sua pessoa. Aí basta compartilhar sua chave via QR Code ou seus dados bancários e receber os recursos de forma mais fácil.</p><p>Novamente, mesmo sem o cadastro das chaves, as pessoas podem te enviar recursos via PIX apenas com seus dados bancários.</p><p>Mais uma questão: <em>“Como tenho certeza que o dinheiro está indo para a pessoa certa?”</em>. Lembra que eu escrevi que o PIX é apenas mais uma uma forma de transferência eletrônica de recursos? Ora, assim como nas transações eletrônicas como TED e DOC, o banco sempre informa o nome completo do destinatário e uma parte de seu CPF antes de completar uma transação PIX, assim você tem certeza de quem vai receber o valor transferido.</p><p>Mais uma vez, o PIX não introduz nenhuma facilidade aos bandidos.</p><p>Outra suspeita que já ouvi sobre o PIX é: <em>“O PIX é parte de um grande plano do governo para monitorar minhas transações!”</em></p><p>Há algumas argumentações importantes sobre esse caso. Primeiro, as movimentações financeiras estão protegidas pelo direito ao sigilo bancário, porém, <a href="http://INSTRUÇÃO NORMATIVA RFB Nº 1571, DE 02 DE JULHO DE 2015">a Receita Federal recebe diversas informações sobre as movimentações financeiras das instituições</a>. Segundo entendimento do STJ, não há quebra de sigilo bancário nesse caso, <a href="https://meusitejuridico.editorajuspodivm.com.br/2020/06/09/o-sigilo-bancario-perante-o-fisco-na-visao-supremo-tribunal-federal/">ocorre apenas um repasse do dever de sigilo da esfera bancária para a fiscal, permanecendo resguardadas a intimidade e a vida privada do correntista.</a></p><p>Nessa seara, o PIX não introduz nada de novo, pois ele é apenas mais uma forma de transferência. Os dados gerados por transferências PIX estão cobertos pela mesmas salvaguardas de sigilo aplicadas às transações bancárias em geral. Se você faz uma TED, não há motivo para não fazer um PIX.</p><h3>Conclusão</h3><p>A segurança do PIX é praticamente a mesma do que a segurança do sistema bancário para qualquer outra forma de transferência bancária. O sistema é mais rápido, mais barato e mais disponível que os demais, logo, em minha opinião, não há motivo para duvidar de sua segurança e eficiência.</p><p>Como nota de encerramento, informo que as informações apresentadas nesse artigo são de minha autoria e não tem relação com o Banco Central do Brasil, onde sou servidor.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=958c0fc9e015" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cryptocurrencies: The Digital Financial Revolution]]></title>
            <link>https://rsarres.medium.com/cryptocurrencies-the-digital-financial-revolution-e531e7222cf6?source=rss-3623df8da039------2</link>
            <guid isPermaLink="false">https://medium.com/p/e531e7222cf6</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Rafael Sarres de Almeida]]></dc:creator>
            <pubDate>Wed, 04 Oct 2017 13:01:06 GMT</pubDate>
            <atom:updated>2017-10-04T13:01:06.877Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the transcript of a talk I gave at the International Policy Centre for Inclusive Growth (IPC-IG) Seminar Series 2017 in July 14th 2017. As I wrote my entire presentation, I thought it would be fun to share it with the world. I hope you enjoy reading it as much as I enjoyed writing it.</p><p>I would like to thank IPC-IG for the invitation to speak about this thrilling subject.</p><p>The slides that I used at the event are available at this<a href="https://www.slideshare.net/rsarres/cryptocurrencies-the-digital-financial-revolution"> Slideshare link.</a></p><h3>1st slide</h3><p>Ladies and gentleman, thank you for the opportunity to speak at the International Policy Centre for Inclusive Growth. Initially, I would like to share important information about this presentation:</p><p>First, the views expressed in this presentation are my own and not necessarily those of my employers;</p><p>And finally, this is not a strictly technical presentation; some simplification was made to fit a broader audience.</p><h3>2nd slide</h3><p>The first topic I would like to address seems simple, but it´s actually a very complicated and fragile social construct: Money.</p><p>The first history I want to share is about the island of Yap in Micronesia. This common island had a very peculiar form of currency in the Middle Ages: Giant limestone disks called Rai Stones. As Yap does not have this kind of mineral, the disks were carved in Palau, another island approximately three hundred miles away. So Yap natives jumped on their rafts and sailed for days to return to their homes a lot richer. This way, Yap currency was only produced through hard, although not very useful, work, keeping inflation rates.</p><p>Obviously, this incarnation of money has a very high transaction cost, it is very difficult to move heavy stones. The solution to this dilemma was simple: They simply did not physically move the disks as they were negotiated to a new owner. A diffuse knowledge about the ownership was created just by propagating the transaction orally throughout the island, establishing a diffuse distributed ledger, a registry with all transactions.</p><p>This convenient solution was so effective that only the knowledge about the physical existence of a stone was needed to create a new unit of currency, making the physical access to the stones unimportant. This way, Rai stones dropped accidentally in the sea during the journey back were accepted. This is an example of a functional currency that lasted for centuries.</p><h3>3rd slide</h3><p>However, history has shown that money is also very fragile and, unfortunately, we have seen some cases of currency destruction by hyperinflation. One of the most notorious examples is the post-World War II Germany. Economically depressed by the heavy penalties imposed by the war winners, German leaders started to print huge sums of their currency, the German mark. Here we can see the “evolution” of the face values of the bills on the course of 1923, going from fifty thousand to fifty billion marks. By the end of year, the national fiat currency had lost so much value that we now can see this historical picture of German mark notes being used as wallpaper.</p><h3>4th slide</h3><p>How can paper currency remain valuable?</p><p>To answer this question, first we need to understand what turns anything desirable. In general, value derives from the combination of utility and scarcity. But when all the basic needs are fulfilled, people tend to attribute psychological value to the most diverse materials and objects. Designer clothes, art objects, diamonds and even gold, all have disproportional evaluation when compared to their real needs in our lives.</p><p>As we have seen, physical form is absolutely unimportant. In digital form, the only way to keep data scarce is to maintain it private. Once it´s released on the internet, it is trivial to create infinite copies and eliminate the scarcity factor in a matter of minutes. We have seen this on the never-ending battle of the entertainment industry against piracy. There is even an interesting phenomenon that happens on the internet that is called the Streisand effect, that is, any attempt to hide information will only amplify its dissemination. The term derives from a Barbra Streisand lawsuit to remove her mansion photograph from a public collection. Before the lawsuit, the image had been downloaded only four times, but over the following month more than 400 thousand downloads were made.</p><p>I know what you are all thinking, so there it is.</p><p>The photo contributes to my point: Digital scarcity is a very complicated attribute to achieve in an open network and that´s why we have not seen a digital fiat dollar bill that we can store in our hard.</p><h3>5th slide</h3><p>Now that we know what makes anything valuable, we can return to our question: “What exactly is money?”</p><p>Money is a social construct that must be relatively scarce so it can function as a store of value medium. Without it, we could not delay our consumption needs as there would be no way to save for an expensive desired object. This is the unfortunate fate of citizens in countries that suffer with hyperinflation in their economies, where they have to run to spend all their salaries as fast as possible before it turns into valueless wallpaper in their pockets.</p><p>Besides storing value, money value must be stable enough to serve as a unit of account in a society, so different items costs can be compared.</p><p>Finally, money must be the instrument used to facilitate trade of goods between parties, acting as a medium of exchange.</p><h3>6th slide</h3><p>So, if money should be scarce and digital scarcity is very difficult to achieve, can digital money exist?</p><p>Actually, digital money exists and it is not new, but it was only possible relying on intermediaries like Banks, Credit Card and Technology companies. They maintain internal ledgers that store all transactions and balances of each participant and the ledger privacy and security is enforced by cybersecurity processes like firewalls, passwords and encryption. Unfortunately, it is not rare to see hacking and data theft from these companies.</p><h3>7th slide</h3><p>Security concerns aside, intermediaries sitting on this privilege position can exclude, censor and commit fraud.</p><p>There is low incentive for many players in the financial sector to deal with the poorer population, denying benefits of a formal financial life like savings and credit.</p><p>Censorship is another problem we have already seen and it is illustrated by the Wikileaks banking blockade in 2010. Whether you sympathize or not with Wikileaks, the financial disablement of an organization was proven to be possible.</p><p>Finally, intermediaries can always tamper with its internal registries. As we have seen in the 2008 financial crisis, lack of proper visibility to assess risk of securities played a big role in all we have seen.</p><p>Even when playing by the rules, intermediaries add friction and cost to the financial sector. A single cross-border payment can pass through four or more financial intermediaries, take almost a week to complete and carry a high fees. The average remittance cost for a busy corridor like United States to Mexico is almost 5%. Exotic corridors are way more expensive, for example, Lebanese people living in Australia must pay a whopping 13% fee to send money to their families.</p><h3>8th slide</h3><p>This need of intermediation is not compatible with the virtual community that was made possible by the internet. A free and equalitarian society desire emerged, as seen on John Perry Barlow´s Declaration of the Independence of Cyberspace, which, I partially quote:</p><p><em>“Cyberspace consists of transactions, relationships, and thought itself, arrayed like a standing wave in the web of our communications. Ours is a world that is both everywhere and nowhere, but it is not where bodies live.</em></p><p><em>We are creating a world that all may enter without privilege or prejudice accorded by race, economic power, military force, or station of birth.</em></p><p><em>We are creating a world where anyone, anywhere may express his or her beliefs, no matter how singular, without fear of being coerced into silence or conformity.”</em></p><p><em>John Perry Barlow</em></p><p>This new world still lacked a fundamental human construct: Money. A new currency was needed, one that was</p><p>anonymous like paper currency,</p><p>anarchic like gold,</p><p>censorship resistant</p><p>and free as the internet.</p><p>In other words, they needed internet money.</p><h3>9th slide</h3><p>What the crypto-anarchists needed was some kind of digital Rai Stone. A currency that could be owned by any virtual citizen, does not rely on any intermediary to maintain the diffuse ownership information and its supply could not be inflated.</p><p>Remembering the digital scarcity problem, it looked like they would need some kind of alien technology to solve this conundrum.</p><h3>10th slide</h3><p>And in 2008, ladies and gentlemen, came Bitcoin to implement a worldwide digital “Rai Stone” without a trusted central authority. It is the first cryptocurrency and has come into existence with the publication of an eight page paper called “Bitcoin: A Peer-to-Peer Electronic Cash System”, published under the pseudonym Satoshi Nakamoto.</p><h3>11th slide</h3><p>And what kind of alien technology does it use? Amazingly, not a single new cryptographic algorithm was developed, but the document describes an innovative way to organize the existing techniques. The resulting technology maintains the diffuse bitcoin ownership information in a distributed public ledger. This data structure is composed by a chain of blocks, thus the name “blockchain”.</p><p>As all ownership information is public, anyone can download the blockchain that is exchanged between nodes using peer-to-peer technology similar to Bittorrent.</p><p>Finally, as the bitcoins keep changing hands, the blockchain is constantly updated with new transactions that are double checked by all network participants against well-known update rules.</p><h3>12th slide</h3><p>Remember one important feature of the Rai Stones: it can be anyone´s property. Similarly, Bitcoin can be owned by anyone with a computer. The only prerequisite to receive a bitcoin is to have a bitcoin address. The 26 to 35 long alphanumeric code derives from an asymmetric public key internally generated by a computer or smartphone running the appropriate software: A Bitcoin Wallet. The absence of information linking bitcoin addresses and real identities makes this payment system pseudonymous.</p><h3>13th slide</h3><p>As asymmetric keys are generated in pairs, the second key must be kept private and will be used to unlock any bitcoin sent to the respective address. The private key is used to sign any transaction that spends a previously received bitcoin. Following peer to peer mode of operation, signed transactions are broadcasted to random connected peers and propagated to every node of the network.</p><h3>14th slide</h3><p>When transactions reach a special node called “Miner”, they are verified upon all protocol update rules like</p><p>· the signature correctness and</p><p>· funds availability.</p><p>Legitimate transactions are grouped into blocks, propagated again to the network in this new form and attached to the blockchain, updating the distributed ledger with the most up-to-date ownership information. Simple, right?</p><p>However, knowing the troll and hacker hordes that reside in the Cyberspace depths, no public database on the Internet can survive without a write access control. The ingenious solution proposed by Nakamoto is a difficult crypto puzzle that implements a proof of work system.</p><p>The crypto-puzzle is similar to a lottery where the chances of winning are proportional to the Miner processing power. Participating in this lottery today requires huge investments in hardware and energy and a one-time winning ticket must be attached to every published block, proving that an investment has been staked in the update proposal. That way, it is expensive to try to tamper with the blockchain.</p><h3>15th slide</h3><p>If a proposed new block is accepted by the network and appended to the blockchain, its miner is rewarded with newly created bitcoins and transaction fees for included transactions. This is the only way bitcoins are created. As nodes locally check the received block thoroughly and will discard it in case of any protocol discrepancy, there is a strong incentive to produce blocks without any fraudulent transactions or currency overcreation.</p><p>If a proposed block is accepted by a node, it is cryptographically chained to the previous block and appended to the blockchain. This interconnection between every block makes it very difficult to tamper with any part of the past blocks because it would invalidate the whole cryptographic chain. In practice, the blockchain data is considered immutable.</p><p>If everything is running as supposed, all nodes are using the same set of consensus rules to evaluate the broadcasted blocks. Using the same input and algorithm, independent nodes will ultimately share a single blockchain view and a single transaction history.</p><p>The blockchain is the digital form of Yap´s Rai stones diffuse ownership information and made digital scarcity possible.</p><h3>16th slide</h3><p>To illustrate what I am talking about, this is a very simple representation of a blockchain. Transactions are stored on each block and the full transaction history can be retrieved simply by reading transactions on each dark green block sequentially. They are in the longest block path where the most work has been staked.</p><p>The light green blocks represent past transient racing conditions. They occur if two blocks are broadcasted at almost the same time, making what path to extend temporarily unclear. When the blockchain is in this state, recent transaction history is undefined until the broadcast of a new block that extends one of the possible paths.</p><p>Malicious nodes can try to fork the blockchain to create a longer path and undo recent transactions, but they must have the majority of the processing power of the network to win the crypto puzzle lottery. Even if they can beat the rest of the network by a couple percent, it is unfeasible to undo transactions on older blocks.</p><h3>17th slide</h3><p>As the only pseudonymous global payment rail at the time, Bitcoin quickly found its perfect use case on the Dark Web, the part of the World Wide Web that is not indexed by standard search engines. It is only accessible by using special software and allows anonymous hosting of websites. Some of these sites are marketplaces for illicit goods like drugs and weapons. As we can all imagine, payments in these global markets were a real problem and Bitcoin was a perfect match for the job. Even with the absolute transparency of the transactions on the blockchain, linking between addresses and real identities is not an easy task.</p><p>That was the first strong use case of the new technology and really boosted its usage outside the libertarian community. This large user base created a market opportunity in exchanging the cryptocurrency for fiduciary money, so the cryptocurrency exchange was born.</p><h3>18th slide</h3><p>The first exchange to trade bitcoins was MtGox, short for “Magic: The Gathering Online eXchange”. What started as a fantasy-based game card exchange service became a multi-million bitcoin exchange handling over 70% of the world´s bitcoin trades. In 2014 the company went bankrupt after an alleged computer hack.</p><p>However, cryptocurrency trading had arrived to stay and now it is a multi-billion market with many huge exchanges operating in different countries.</p><h3>19th slide</h3><p>Not only new exchanges were created, but new cryptocurrencies kept pouring in. Today we know more than 800 different cryptocurrencies in circulation, some are mere copies of the bitcoin reference code, but others implement new features like transaction obfuscation in Zcash and programmability in Ethereum.</p><h3>20th slide</h3><p>The consequence of the development of this ecosystem is a global payment rail that any person can use just a mobile phone to send value globally. A</p><p>mobile,</p><p>private,</p><p>borderless,</p><p>fraud and censorship resistant,</p><p>irreversible and</p><p>programmable payment system was born.</p><p>Just to put this breakthrough in perspective, let´s ask ourselves what thing we would carry if we ever needed to run for our lives. I think we would certainly agree: We would carry our smartphones. International Rescue Committee arrived at the same conclusion when they surveyed the bags of refugees: They all carried a smartphone. And now, besides communication and information, they can carry value in their smartphones and receive aid from any person in the world without an intermediary.</p><p>This, ladies and gentleman, is truly amazing.</p><h3>21st slide</h3><p>And it does not stop there. Blockchain technology can disrupt many sectors with new and ingenious use cases that previously required a trusted third party. Digital rights, title records, digital global identity, crowdfunding, p2p lending, property ownership; all these uses are being actively researched and some of them are already available.</p><p>In a near future we might interact with a blockchain to secure a rental deposit while an Internet of Things lock allows access to a shared car or vacation apartment. This would be a new marketplace intermediated only by a blockchain.</p><h3>22nd slide</h3><p>As we all know, innovation is never a bed of roses. Like in old movies, we always have the good, the bad and the ugly sides.</p><p>On the good side, value movement freedom allows us to boost good actions like refugee aid and lower remittance cost and time.</p><p>However, on the bad side, the same freedom that allows us to reach the underprivileged can assist criminals. The free flow of value can be exploited to launder money and finance terrorists.</p><p>Finally, the ugly side: The blockchain technology is still very immature, sketchy and inefficient. Bitcoin miners, for example, collectively consume as much energy as a small country to secure only around FIVE to SEVEN transactions per second globally.</p><h3>23th slide</h3><p>As in many technological disruptions, regulators are called to address the bad side. They must protect citizens mitigating unacceptable risks while encouraging the beneficial innovation disruption. It has happened with Uber, it is happening with cryptocurrencies.</p><p>That way, financial regulators must evolve from risk managers to responsible innovation gateways, acting very carefully to address harmful activity while fomenting beneficial technology.</p><p>It may look like an easy task, but achieving the right balance is very difficult.</p><h3>24th slide</h3><p>On the ugly side, let´s remember:</p><p>The first car was inefficient, slow, dangerous and unreliable.</p><p>However, today we can have a clean, fast, safe and reliable one.</p><h3>25th slide</h3><p>The same happened with first browser. It was very slow and limited, but it proved the amazing potential of the World Wide Web.</p><p>But today we have full featured browsers that can handle complex web pages with animation, scripts, sound, video and even 3D rendering. However, no browser was ever able to transfer value without intermediaries.</p><h3>26th slide</h3><p>Well, Bitcoin closed this gap, but it was built on top of the first blockchain ever designed. It is slow, inefficient and awkward, but people have tasted freedom.</p><p>The genie won´t go back to the bottle.</p><p>So, what lies ahead in this technology?</p><p>I see no other path other than constant improvement that will power the Digital Financial Revolution.</p><h3>27th slide</h3><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e531e7222cf6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proposal for a backup RTGS using blockchain technology part 2: hiding transaction data]]></title>
            <link>https://rsarres.medium.com/proposal-for-a-backup-rtgs-using-blockchain-technology-part-2-hiding-transaction-data-70269849aa7f?source=rss-3623df8da039------2</link>
            <guid isPermaLink="false">https://medium.com/p/70269849aa7f</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Rafael Sarres de Almeida]]></dc:creator>
            <pubDate>Mon, 29 May 2017 19:41:09 GMT</pubDate>
            <atom:updated>2018-02-09T14:51:28.746Z</atom:updated>
            <content:encoded><![CDATA[<p>Last October <a href="https://medium.com/@rsarres/proposal-for-a-backup-rtgs-using-blockchain-technology-f14bb92c25d3">I wrote</a> about a blockchain Real-time Gross Settlement (RTGS) and now I am ready to write some more about what I have been researching to improve the proposal. One of the main problems of the first version was the publicity of all transactions between banks because the smart contract hid the balances, but exposed everything else.</p><p>As the balances are not verified by the contract logic, the transaction data does not need to be stored in clear text. So a new version of the BlockchainRTGS smart contract was developed to store only encrypted transaction data. All decrypting and data processing is done offline.</p><p>The transaction cryptography uses symmetric and asymmetric cryptography. A unique symmetric key is generated by the Central Bank for each pair of banks participating in the network. For example, if there are <em>n</em> banks participating in the blockchain RTGS system, (<em>n</em>.(<em>n</em>-1))/2 symmetric keys must be used.</p><p>The contract stores each banks´s certificate and the symmetric keys asymmetrically encrypted twice: One using bank A´s public key and the another using bank B´s. So each can decrypt its transaction key with its private key and read all transactions that it is part of.</p><p>All pretty basic and functional, but two things bothered me: the <a href="https://en.wikipedia.org/wiki/Forward_secrecy">forward secrecy</a> absence and the offline overdraft protection. The first drawback means that, as every network participant has access to a lot of historical encrypted data, they can read all past transactions in case of key leaks by mismanagement, hacks or <a href="https://en.wikipedia.org/wiki/Cryptanalysis">cryptanalysis</a>. The second problem derives from the impossibility for the smart contract to automatically block transactions from senders that do not have enough money to honor them. That´s why a transaction log and Central Bank transaction blocking system was implemented on the first post, but here we are again relying on a central party. As explained in the original post, the RTGS system still operates relying on honest behavior incentive. Not the best solution, but, at least, it is an an option to total financial system freeze.</p><h3>JPMorgan Chase Quorum: A new hope</h3><p>When I learned about <a href="https://github.com/jpmorganchase/quorum">JPMorgan´s Quorum</a> I got pretty excited that it would solve this problem. Maybe the recipient bank could even be sure that the sender had enough balance without the need of a Central Bank node present on the network. (<em>Spoiler alert: AFAIK, for now it can´t.)</em></p><p>Quorum is an Ethereum fork that implements transaction and contract privacy in a distributed ledger. It adds two main features to the Ethereum protocol: a new consensus model based on voting mechanism (QuorumChain) and a new peer-to-peer private message exchange (Constellation).</p><p>I used the provided Vagrant example (7 nodes) to develop the prototype of the BlockchainRTGS running on JPMorgan Quorum: the 5nodesRTGS. This environment starts 5 instances of quorum nodes and provides scripts to get everything up and running.</p><p>Working with Quorum is very similar to working with with Ethereum, are some minor changes and additional commands in the command line. The first thing I had to understand was how private transactions work.</p><p>Different from Ethereum, Quorum can use Constellation to send messages directly to defined recipients in the parameter “<em>privateFor”</em> represented as public keys, creating encrypted private transactions. If a private transaction creates a contract, it is created as a private contract. Private transactions and contracts obviously are not part of the consensus process as the data stored on different nodes are simply not the same. Quorum creates a separated Merkle Patricia trie to store the private contracts states.</p><h3>Getting everything running</h3><p>The test environment is available as a new Quorum example at <a href="https://github.com/bacen/quorum-examples">this github</a> fork. The README file explains how to get the network up and running. The two smart contracts developed are available in the <em>contracts.sol</em> file: <em>bankContract </em>and <em>regulatorTransactionList. bankContract </em>is deployed privately and stores the sensitive data and<em> regulatorTransactionList </em>is deployed as a public contract and provides the public transaction log and bank data.</p><p>Instead of sharing a unique smart contract that stores all banks information as the previous BlockchainRTGS, it is mandatory to create a private contract instance <em>for each</em> participating bank <em>on all nodes </em>when using Quorum. In my test, the chosen nodes are:</p><ul><li>Node 1: Bank 1;</li><li>Node 2: Bank 2;</li><li>Node 3: Bank 3;</li><li>Node 4: Regulator;</li><li>Node 5: Observer.</li></ul><p>After contract deployment detailed in the README, the regulator node can populate the contracts with private data. For example: The balance variable (initially zero) of bank A was set using a message created by the regulator node destined (<em>privateFor</em>) only to banks 1´s node. After this message, the balance variable (and the contract state, obviously) in the <em>same</em> smart contract address has different states between nodes: Bank 1´s contract on bank 2´s node still has balance zero. That´s why private contracts cannot be part of the consensus rule.</p><p>Let me illustrate with some output after initial deployment:</p><p>Output from Node 1 (bank 1):</p><pre>&gt; contract1.balance()<br>10000<br>&gt; contract2.balance()<br>0<br>&gt; contract3.balance()<br>0</pre><p>Output from Node 2 (bank 2):</p><pre>&gt; contract1.balance()<br>0<br>&gt; contract2.balance()<br>20000<br>&gt; contract3.balance()<br>0</pre><p>Output from Node 3 (bank 3):</p><pre>&gt; contract1.balance()<br>0<br>&gt; contract2.balance()<br>0<br>&gt; contract3.balance()<br>30000</pre><p>Output from Node 4 (regulator):</p><pre>&gt; contract1.balance()<br>10000<br>&gt; contract2.balance()<br>20000<br>&gt; contract3.balance()<br>30000</pre><h3>The private consensus absence</h3><p>I must confess: I took a while to change my blockchain trained brain to deal with different states of the same contract. Countless times I coded a smart contract logic just to remember that I could not use the private data on the wrong node. I finally realized that I still need a Regulator node to act as an accountant to the participants and to stop any transaction that would cause an overdraft. This unfortunately is a big problem to my totally decentralized Quorum RTGS goal.</p><p>Nevertheless, I kept on programming. Quorum could still be a step forward to the last version where the encrypted data was available to all nodes. (<em>Spoiler alert: It can!)</em></p><h3>Enter the bug parade</h3><p>I slowly realized that I needed support variables to inform the smart contract logic about where this specific instance of the smart contract is hosted. Without them, it was impossible to take correct actions.</p><p>My mistake was to think think about inter-contract interactions as inter-node interactions. In my initial reasoning, a local smart contract was invoking another bank´s contract in the bank´s node, but in reality, every smart contract is processed locally invoking local instances of other banks contracts as in all Ethereum nodes. The only node where all data is available is the regulator node. I really struggled to get the grip of this kind of logic inverse to blockchain´s full data availability and transparency, but finally achieved a working version it after a lot of awful crazy bugs.</p><p>That said, the final smart contract has support variables that guide the processing logic like <em>isRegulatorNode</em> and <em>thisBankContract</em> that are privately set by the Central Bank node<em>. </em>These variables store information about the node this contract is hosted in like if it is in the Central Bank node and the local bank node contract address, respectively.</p><p>The last problem was how to create an unique transaction ID when there was no global data store. So I added a public support smart contract to store global information, but public contracts can only be read by private contracts, not written. This is makes sense as a private update on a public contract would break consensus as private contracts can behave differently on different nodes.</p><p>Long story short: I blatantly copied the public blockchains solution: The transaction ID is a hash derived from the transaction data. Still, two transactions with the same sender, recipient and value would generate the same hash. To add some randomness to the equation, I included the block timestamp to the hash calculation. This did not solve the problem completely because a fast stream of equal transactions included in the same block produce the same hash. I tried to add <em>msg.data</em> to the hash input with the same result because the transaction nonce is not included in this global variable. Without any better solution, I added an offchain generated <em>random </em>parameter to the <em>sendValue </em>function that is used in the hash calculation. If it is really random, transaction IDs collision should be REALLY improbable.</p><p>As explained, the private <em>bankContract</em> can´t update the public <em>regulatorTransactionList</em> contract, so this must be done by the sender. Transactions not present in the public transaction log cannot be confirmed, even by the regulator. During the development of this part public-private interaction, I bumped into a Quorum private-public contract interaction <a href="https://github.com/jpmorganchase/quorum/issues/82">bug</a>, but the very helpful Quorum community pointed to a quick workaround in no time.</p><p>Transaction confirmation was kept mainly unchanged from <a href="https://medium.com/@rsarres/proposal-for-a-backup-rtgs-using-blockchain-technology-f14bb92c25d3">the last post</a>, the offline balance is achieved by the regulator node inspecting every transaction and blocking the overdraft ones during the confirmation time, shown in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*JckPweBos-M1KI1wdznUYw.jpeg" /><figcaption>Offline overdraft protection</figcaption></figure><p>Using the public transaction log, I am sure that the regulator can see all the transactions and, if it was not blocked after the confirmation time (10 minutes in this example), one of two scenarios had taken place:</p><p>1- The sender has enough funds.</p><p>2- The sender does not have enough funds AND the regulator is offline.</p><p>On either case, the recipient can accept the funds because they follow the rules of the blockchain RTGS. If the regulator cannot tolerate any overdraft transaction, he would have disabled the bank´s self-confirmation function, but in this case there is no point in using a distributed blockchain solution after all. If it is enabled, the regulator opted for resiliency instead of strict compliance.</p><h3>Bottom line…</h3><p>I believe that this prototype is a small step towards the completely distributed blockchain RTGS. Using the privacy features of JPMorgan Quorum, the system does not rely anymore in offline cryptography of transaction and balance data of the smart contract, so no more encrypted private data floating around. All data stored in Quorum private smart contracts is obviously private between whoever received the private transaction. The drawback is the lost of consensus about the contract state, so no automatic positive balance enforcement was achieved, Quorum blockchain RTGS still relies on an active regulator node to block overdraft transactions as before. It is not the perfect solution I want yet, but a better solution than before nevertheless.</p><h3>Stop the presses!</h3><p>As I was writing this article, great news have been published: <a href="http://www.ibtimes.co.uk/zero-knowledge-proofs-added-jp-morgans-quorum-blockchain-1622573">Quorum will support zero-knowledge proofs!</a> Maybe this witchery…, er, technology is the key to my problem. It makes a lot of sense: I need to prove that a bank has enough funds but I cannot show how much money it has.</p><p>Well, I can only say there is at least one guy that is eagerly waiting for this update.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70269849aa7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Votebook a really private blockchain voting system?]]></title>
            <link>https://rsarres.medium.com/is-votebook-a-really-private-blockchain-voting-system-919093488782?source=rss-3623df8da039------2</link>
            <guid isPermaLink="false">https://medium.com/p/919093488782</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[elections]]></category>
            <dc:creator><![CDATA[Rafael Sarres de Almeida]]></dc:creator>
            <pubDate>Fri, 03 Mar 2017 13:54:55 GMT</pubDate>
            <atom:updated>2020-11-18T19:21:07.156Z</atom:updated>
            <content:encoded><![CDATA[<p>Elections are a very complex process. The basic assumptions are contradictory: Voters must be registered and cast only one vote, but votes must be kept private and cannot be linked to its voter by an external entity. Using conventional paper ballots and every candidate had at least one vote, there is no way for a citizen to be sure that his vote was really counted. A candidate can claim all his family voted for him, but there is no way to prove anything beyond your own vote that you obviously know. Frauds have taunted countries for ages without a good answer from the world´s IT department in developing a secure and anonymous digital voting system.</p><p>Wait, don´t I live in Brazil where the elections are completely electronic? Yes, Brazil has an electronic voting system, but it has never gone through extensive and open security tests. First, the code is not open source, so no researcher can freely study the program that runs in the voting machines. Even the machine hardware is not available to an open examination. The Superior Court of Elections is the branch of the government that defines the election process in Brazil, develops the code and defines the machine hardware specs. They recently promoted a public test that provided access to the voting machine and code to researchers for a brief time and under very restrictive rules. Even on a absolutely constrained environment, a group of <a href="http://www.kegles.com.br/wp-content/uploads/2015/07/relatorio-urna.pdf">researchers was able to recover the order of the votes</a>, which is pretty serious for the elector privacy. Moreover, Brazil´s voting machines do not print paper ballots to allow manual recounting, so we have to trust on the digital results alone.</p><p>This problem let to a <a href="http://www.economist.com/whichmba/mba-case-studies/cyber-security-case-study-competition-2016">challenge</a> promoted by Kaspersky Lab and The Economist magazine: Can blockchain technology really hold the key to secure digital elections?</p><p>The requirements seemed to cover all the voting system basics:</p><p>1- Privacy;</p><p>2- Voting under duress protection;</p><p>3- Partial results disclosure avoidance before all voting spaces are closed;</p><p>4- Correct counting of blank votes and abstainers;</p><p>5- Recounting possibility;</p><p>And a final important requirement:</p><p>6- Ability to check that your vote was really counted.</p><p>The winner was New York University with its <a href="http://www.economist.com/sites/default/files/nyu.pdf">Votebook proposal</a>. As a blockchain enthusiast living in Brazil, I read the paper, which, spoiler alert, had very good insights but, in my opinion, falls short under severe security scrutiny.</p><p><strong>How Votebook works</strong></p><p>The NYC team proposed a system that relies on a “permissioned blockchain” using dedicated voting machines on designated poll locations. Remote voting was not permitted because of coercion, personal device compromise and denial of service risks. Good call, in my opinion. Prior election day, each voter must have a unique <em>voter ID that </em>can be a randomly generated number or a previous unique public identification ID like a driver´s license. Each voting machine must generate an asymmetric key set and send its public part to a central authority server that compiles a complete trusted public key table, appends signatures from all voting machines and loads the complete signed trusted public key list on each voting machine.</p><p>Once the pools open, the machines will connect to each other in a peer-to-peer network protected by a Virtual Private Network through the internet and start collecting the votes. Each voter must input his <em>voter ID</em> in the machine, write the choices and if he is under duress. A <em>ballot ID</em> is generated for the voter and printed to be taken out. A hash is generated from the concatenation of the <em>ballot ID</em> and the <em>voter ID, </em>I will call it <em>interaction ID</em>. The “voting under duress” is signaled generating a <em>ballot ID</em> that produces a character in a position of the <em>interaction ID</em> hash. A receipt is printed and deposited in a secure space containing <em>interaction ID </em>and the vote choices. This is the best design choice of the team: Paper audit. It is not clear, but it is important that this paper receipt can be verified by the voter thought a transparent window before being deposited without any possibility of manual intervention.</p><p>Behind the scenes, the machines aggregates the votes in a block composed of a set of data structures [<em>interaction ID</em>,votes], a standard blockchain hash of the previous block and a digital signature. These blocks are broadcast to the peer-to-peer blockchain network, and its signature is validated on arrival using the trusted public key table. This vote ledger allow partial results disclosure if permitted.</p><p>A second ledger is proposed on the same peer-to-peer network: A voter ledger. This blockchain propagates all the <em>voter IDs</em> that have already cast a vote and is intended to detect and discard any double-voting.</p><p><strong>Votebook really improves the fraud resistance, but at an expensive cost</strong></p><p>I understand the Votebook motivation. In the actual voting system, we cannot be 100% sure if our personal votes were really counted or if absent voter names were used to cast fraudulent votes. The NYC blockchain voting system permits all voters to check if his vote is in the public ledger that stores all votes.</p><p>But what bothers me is the cost of this feature. I live in Brazil and in every election we watch the news being flooded with voter bribery and coercion. Votes are exchanged to the most variable sort of things, from money to dentures, but today an elector can simply take the bribery and vote for the other candidate. Being able to check to whom you have voted for means that the briber will attach some strings to his offer, after all he wants to be sure if the voter fulfilled his part of the deal. Things will get even worse in case of threats instead of bribery. Everyone will vote for a violent candidate because he will knock on your door after the election to collect your <em>ballot ID.</em></p><p>The last problem I see is the constant internet connection on every machine during election day. I do not have to explain how dangerous it is. The authors explain that <em>“the machines will never touch the open web”</em> because they only communicate through virtual private networks (VPNs) and firewalls will restrict communication. In my opinion, this is not the same as “never touch open web”. Any vulnerability on the firewall or VPN software will compromise everything, and the attackers incentives are high. My definition of “never touch open web” is an air gap. Without it, we cannot be sure that the machine is not leaking all <em>ballot IDs</em>.</p><p><strong>Closing thoughts</strong></p><p>In my opinion, Votebook is a step forward but it cannot be used in unsecure countries like Brazil. It improves the accountability of an election on expense of voter privacy. Using this system, voters can check if your vote was really counted, but opens a silent attack vector that discloses how every voter voted, task actually much more difficult using conventional paper ballots.</p><p>I really like the idea that a voter should be able to check that his vote was properly counted, but I can´t think in a way of doing it without destroying the voter privacy in a country where the state does not properly protect its citizens.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=919093488782" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proposal for a backup RTGS using blockchain technology]]></title>
            <link>https://rsarres.medium.com/proposal-for-a-backup-rtgs-using-blockchain-technology-f14bb92c25d3?source=rss-3623df8da039------2</link>
            <guid isPermaLink="false">https://medium.com/p/f14bb92c25d3</guid>
            <category><![CDATA[rtg]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[central-bank]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Rafael Sarres de Almeida]]></dc:creator>
            <pubDate>Mon, 03 Oct 2016 03:06:30 GMT</pubDate>
            <atom:updated>2017-03-09T02:10:45.985Z</atom:updated>
            <content:encoded><![CDATA[<p>Real-time Gross Settlement (RTGS) is the base structure for a country payment system. Brazil, for example, has a very advanced RTGS system called “<em>Sistema Brasileiro de Pagamentos</em>” (Brazilian Payment System), or SPB, run by Central Bank of Brazil.</p><p>By its own nature, this is a critical technological structure for the national financial system because all banks reserves are exchanged through it. In the case of a total failure, no bank can send or receive funds, it is a complete financial freezing.</p><p>So, giving the features and drawbacks of the blockchain technology, can it help to maintain a minimal real-time settlement system in place in case of a catastrophic event that takes the main RTGS system and every Central Bank(CB) datacenter down? This is what I will try to explore in this post.</p><h3>The basis</h3><p>Let´s start listing the relevant features of the blockchain technology:</p><p>1- Immutability</p><p>2- Fraud resistant</p><p>3- Censure resistant</p><p>4- Transparency</p><p>First, the useful ones: Immutability, fraud and censure resistant. They assure that all transactions are authenticated by the correct parties, will be processed without third party intervention and that the code is executed exactly as programmed. The problematic one is is transparency. In a RTGS system, the balance of any participant is a sensitive data as it can show that an institution is on the verge of default. Let´s see how to handle it.</p><p>The basis of this backup RTGS system is obvious: Build a blockchain network where every financial institution and the central bank are miners and use the Internet as network due to its resiliency. In this case they would share the same distributed ledger that stores the state of every bank financial reserve and they could make transactions <strong>even in the absence of a Central Bank, governed only by smart contracts</strong>.</p><p>This blockchain must be in place even during main RTGS operation to be kept constantly updated with the most recent positions of every player, but locked for any transactions that must be sent though the main RTGS system when operational. I call this <strong>PRE-OPERATION</strong> status.</p><p>In the case of a total meltdown of the IT or physical structure that supports the primary RTGS, a crisis committee in the CB should be scrambled as previously determined by the contingency plan and decide if the backup blockchain RTGS should be activated, passing it to the <strong>OPERATIONAL</strong> status. If positive, the CB would write a global public variable using a simple smart contract transaction that is signed by its private key, of course. So no need to sign the actual data that it´s being written.</p><p>First question: If there is no IT system still working in the Central Bank, how can it send the “Blockchain RTGS change to OPERATIONAL status” message?</p><p>I have two ideias: The first one is the use a cloud infrastructure ready to send this start order. This ideia may not be accepted because of security constraints and the lack of trust in the cloud providers for such a critical element.</p><p>My second idea is to provision physical tokens with the Central Bank´s private key and notebooks with the blockchain software installed and distribute them geographically. This IT equipment and someone with the token PIN is everything that is needed for an authorized CB employee change the OPERATIONAL status.</p><h3>Hiding the balances</h3><p>As stated before, the balances are sensitive information and must be kept private between CB and financial institutions. So it cannot be written in clear in the blockchain. My proposal is to write each financial institution balance in the blockchain ciphered with its respective public key, so the banks can only read your own balance.</p><p>Having an obfuscation mechanism applied on blockchain data is useful but has a major problem: As the smart contracts run by the miners must execute exactly the same in every miner, no use of the deciphered balance data can be made by the smart contract as only two miners can decipher it: CB and the balance owner.</p><p>So my idea is to store only relative balances in the Blockchain RTGS after transaction execution. This relative balance is initialized with zero and fluctuates between positive and negative numbers reflecting the distance to the initial balance. No balance validation can be checked by the smart contract before any transaction, so this task must be made off-chain. The institution should validate for itself if it has enough money prior sending a money transfer transaction to the network.</p><h3>Honest behavior incentive</h3><p>Well, if the positive balance is not enforced by the blockchain smart contract, what are the incentives for the bank not to transfer beyond its reserves?</p><p>My proposal is to have a variable (ALLOWED) for each financial institution that can only be written by the CB stating that this specific bank can make transactions on the Blockchain. So the function in the smart contract that sends money between entities can only be called by a bank that have the ALLOWED variable set.</p><p>This permission to make transactions can be revoked at anytime by the CB if it has a node operational on the blockchain network and can monitor each bank reserves comparing the relative balance with the deciphered initial balance. This can only be made by a system that runs outside be blockchain, but uses data written in the blockchain in real-time. If a bank makes a transaction that exceeds its available initial reserve, the CB can write on the blockchain changing its ALLOWED variable to FALSE, blocking all further transactions from this participant.</p><p>If the financial institutions does not know all the possible CB nodes IP addresses, the participation of the CB in the network cannot be determined in advance, creating a “<em>culture of compliance” </em>that shapes the behavior even if the CB is not participating in the Blockchain RTGS network because it is still handling its IT crisis and getting its supervision staff ready. In any case, the RTGS can operate even without a Central Bank with some degree of compliance.</p><h3>The last transaction problem</h3><p>The system defined above has a major flaw: A bank that already knows that it is insolvent can make a last big transaction before going under. To solve this problem, I designed a system of transaction logs.</p><p>Every transaction is written in a transaction log in the blockchain and is initialized with an UNCONFIRMED state. A transaction is only executed and changes the relative balances of both parties if confirmed, so an unconfirmed transaction is like an unconfirmed transaction in the Bitcoin protocol: It has not happened, no money has changed hands.</p><p>The transaction creator can confirm its own transaction only AFTER waiting for a number of confirmation blocks (the verification phase), but only if:</p><p>a. the transaction has not been blocked by the CB.</p><p>b. the bank has not been blocked by the CB.</p><p>Using this transaction confirmation system, the Central Bank can verify all transactions in real-time during the verification phase before they can be executed. The CB can block any transaction of a bank that does not have enough funds to honor it. If the CB is not active and monitoring transactions written in the blockchain, all transactions can be confirmed after some blocks are created on top of it.</p><p>There is a strong incentive in this blockchain RTGS system not to create invalid transactions as there is a high probability that the Central Bank is checking all the transactions prior their execution. It the CB is offline and this information is not known by the banks, we have a RTGS without an active Central Bank.</p><h3>Enough talk, show me the code</h3><p>I wrote this Solidity smart contract to test the ideas above and it works well in my local Ethereum lab. I did not test the off-chain balance validation but in my opinion it is trivial.</p><pre>contract BlockchainRTGS {<br> <br>address public centralBank;<br>bool public operational; <br>uint public confirmationBlocks;<br>uint public totalTransactions;<br> <br>struct Banks {<br> string name;<br> bool allowed;<br> bool exists;<br> int relativeBalance;<br> string encryptedBalanceForBank;<br> string encryptedBalanceForCentralBank;<br>}</pre><pre>struct Transaction {<br> uint blockNumber;<br> address senderBank;<br> address rcptBank;<br> int value;<br> bool confirmed;<br> bool allowed;<br>}<br> <br> <br>mapping (address =&gt; Banks) public balances;<br>mapping (uint =&gt; Transaction) public transactionLog;<br> <br> <br>function BlockchainRTGS(){<br> <br>centralBank=msg.sender;<br>operational=false;<br>totalTransactions = 0;<br>confirmationBlocks = 10; <br>}<br> <br>modifier onlyOwner() { if (msg.sender != centralBank) throw;_<br>}<br> <br>modifier onlyIfAllowed() { if (!balances[msg.sender].allowed) throw;_<br>}</pre><pre>function makeOperational() onlyOwner {<br> operational=true;<br>}</pre><pre>function changeConfirmationBlocks(uint _confirmationBlocks) onlyOwner {<br> confirmationBlocks=_confirmationBlocks;<br>}</pre><pre>function addBank (address _bank, string _name) onlyOwner {<br> <br>balances[_bank].relativeBalance = 0;<br>balances[_bank].allowed = true;<br>balances[_bank].exists = true;<br>balances[_bank].encryptedBalanceForCentralBank = “”;<br>balances[_bank].encryptedBalanceForBank = “”;<br>balances[_bank].name = _name;<br>}</pre><pre>function updateBalance(address _bank, string _encryptedBalanceForCentralBank, <br>string _encryptedBalanceForBank) onlyOwner {<br> balances[_bank].encryptedBalanceForCentralBank = _encryptedBalanceForCentralBank;<br> balances[_bank].encryptedBalanceForBank = _encryptedBalanceForBank;<br>}<br> <br>function createTransaction(address _rcptBank, int _value) onlyIfAllowed returns (uint) {<br> <br> if (!balances[_rcptBank].exists) throw;<br> if (!balances[msg.sender].exists) throw;<br> if (!operational) throw;</pre><pre>transactionLog[totalTransactions++] = Transaction(block.number,msg.sender,_rcptBank,_value,false,true);<br> <br> return totalTransactions-1;<br> <br>}</pre><pre>function confirmTransaction(uint _transaction) onlyIfAllowed {<br> if ((msg.sender != transactionLog[_transaction].senderBank) &amp;&amp;<br> (msg.sender != centralBank)) throw;<br> if (!transactionLog[_transaction].allowed) throw;</pre><pre>if (block.number-transactionLog[_transaction].blockNumber &lt; confirmationBlocks) throw;<br> <br> balances[transactionLog[_transaction].senderBank].relativeBalance -= transactionLog[_transaction].value;<br> balances[transactionLog[_transaction].rcptBank].relativeBalance += transactionLog[_transaction].value;<br> transactionLog[_transaction].confirmed=true;<br>}</pre><pre>function blockBank(address _bankToBlk) onlyOwner {<br> balances[_bankToBlk].allowed = false;<br>}</pre><pre>function unblockBank(address _bankToBlk) onlyOwner {<br> balances[_bankToBlk].allowed = true;<br>}</pre><pre>function blockTransaction(uint _transaction) onlyOwner {<br> transactionLog[_transaction].allowed = false;<br>}</pre><pre>function unblockTransaction(uint _transaction) onlyOwner {<br> transactionLog[_transaction].allowed = true;<br>}</pre><pre>function kill() onlyOwner {<br> suicide(centralBank);<br>}<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f14bb92c25d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>