<?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 Dmitry Laptev on Medium]]></title>
        <description><![CDATA[Stories by Dmitry Laptev on Medium]]></description>
        <link>https://medium.com/@x0100?source=rss-31fdaacddcaa------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HNYY0qfHcT7kS8yG_AfL3Q.jpeg</url>
            <title>Stories by Dmitry Laptev on Medium</title>
            <link>https://medium.com/@x0100?source=rss-31fdaacddcaa------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 02:29:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@x0100/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[Про дефляционную экономику]]></title>
            <link>https://x0100.medium.com/%D0%BF%D1%80%D0%BE-%D0%B4%D0%B5%D1%84%D0%BB%D1%8F%D1%86%D0%B8%D0%BE%D0%BD%D0%BD%D1%83%D1%8E-%D1%8D%D0%BA%D0%BE%D0%BD%D0%BE%D0%BC%D0%B8%D0%BA%D1%83-bef5aa4c596?source=rss-31fdaacddcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/bef5aa4c596</guid>
            <category><![CDATA[австрийская-школа]]></category>
            <category><![CDATA[инфляция]]></category>
            <category><![CDATA[дефляция]]></category>
            <category><![CDATA[биткоин]]></category>
            <category><![CDATA[экономика]]></category>
            <dc:creator><![CDATA[Dmitry Laptev]]></dc:creator>
            <pubDate>Thu, 27 Jun 2019 08:52:23 GMT</pubDate>
            <atom:updated>2019-06-27T08:52:23.281Z</atom:updated>
            <content:encoded><![CDATA[<p>Биткоинов ограниченное количество, а значит биткоин-экономика будет дефляционной…</p><p>“Но ведь все знают, что небольшая инфляция полезна для экономики, а дефляция приводит к стагнации” — это утверждение настолько распространено, что большинство людей (в том числе экономистов) даже не задумываются над его справедливостью.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*RcW72cvGbvbP3YCLdpQgPA.png" /><figcaption>Общее количества монет и проецируемый уровень инфляции биткоина (<a href="https://bitcointalk.org/index.php?topic=130619.0">источник</a>).</figcaption></figure><p>Я нисколько не претендую на звание эксперта в этой области, но считаю что стоит как минимум знать о существовании альтернативной точки зрения на этот вопрос.</p><h4>Определение</h4><p>Итак, <strong><em>инфляция</em></strong> — это когда цены на товары и услуги увеличиваются, <strong><em>дефляция</em></strong> — когда уменьшаются.</p><p>Сильно упрощая, в большинстве случаев инфляция и дефляция напрямую связаны с монетарной политикой центральных банков. Еще сильнее упрощая, они связаны с тем, насколько активно центральный банк печатает новые деньги.</p><blockquote>Интересный факт #1. Раньше инфляция и дефляция напрямую определялись как увеличение/уменьшение общего количества денег в циркуляции. Но банковская система настолько усложнилась (гуглите “fractional reserve”), что эмиссию денег теперь оценить точно практически невозможно.</blockquote><h4>Традиционный взгляд</h4><p>Традиционная Кейнсианская школа экономики придерживается взгляда, что небольшая инфляция необходима для экономики.</p><p>Растущие цены приводят к тому, что людям и корпорациям выгоднее не хранить свои деньги, а тратить и реинвестировать их, стимулируя таким образом спрос. Спрос стимулирует предложение, производство растет, экономическая машина работает.</p><p>Если же вдруг случается дефляция, то наступает коллапс экономики. Цены падают, люди тратят меньше денег, производство падает, безработица растет, цены падают еще сильнее, и так далее.</p><p>В качестве примеров негативного влияние дефляции обычно приводят Великую депрессию США в 1930-е годы и дефляционную спираль Японии в 1990-е годы.</p><blockquote>Интересный факт #2. По самым осторожным оценкам, за последние 50 лет американский доллар потерял более 85% своей стоимости за счет инфляции.</blockquote><h4>Альтернативный взгляд</h4><p>Но существуют еще другие школы экономики, например <a href="https://ru.wikipedia.org/wiki/%D0%90%D0%B2%D1%81%D1%82%D1%80%D0%B8%D0%B9%D1%81%D0%BA%D0%B0%D1%8F_%D1%88%D0%BA%D0%BE%D0%BB%D0%B0">Австрийская</a>, и они придерживаются других взглядов, которые при ближайшем рассмотрении оказываются вполне разумными.</p><p>В частности они утверждают, что уменьшающиеся цены не приводят в общем случае к сильно драматичному уменьшению спроса. Разумеется, люди не перестанут покупать еду и другие обязательные товары. Но они также не перестанут полностью покупать и предметы роскоши.</p><p>Например, в технологическом секторе сейчас наблюдается локальная дефляция: новый телефон, который в этом году стоит 1000 долларов, через два года будет стоить 800. При этом люди все равно очень активно покупают новые телефоны.</p><p>Но это, конечно, анекдот, а не наука. Что же будет, если погрузиться глубже непосредственно в данные? Оказывается, что в этом случае “типичный” пример Японии выглядит очень даже нетипичным.</p><p>Экономисты Atkeson и Kehoe провели <a href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=495773">исследование</a> периодов дефляции и экономической депрессии в разных странах за последние 180 лет и выяснили, что из 73 периодов дефляции 63 не приводили к снижению экономической активности, а из 29 периодов депрессии 21 приходился на период инфляции, а не дефляции.</p><h4>Здоровая дефляция</h4><p>Никто не спорит с тем, что большая дефляция действительно приведет к коллапсу экономики. Последствия будут ничуть не лучше, чем в случае гиперинфляции (кстати наблюдаем намного чаще, чем дефляционную спираль).</p><p>Но небольшая дефляция или нулевая инфляция <em>в идеальном случае</em> приведут к вполне вменяемым последствиям, с которыми рыночная экономика должна отлично справиться сама.</p><p>— Ценность денег не будет размываться инфляцией, люди и компании смогут сохранять свои заработки.</p><p>— Станет сложнее отдавать долги (а следовательно и брать в долг); Те, кто набрал очень много долгов — объявят себя банкротами и уйдут из бизнеса; Многие долги будут рефинансированы на более выгодных условиях.</p><p>—Государствам придется функионировать на налоговые деньги, а не на напечатанные; Меньшее количество долгов приведет к более плавному развитию экономики (меньше возможностей для образования пузырей).</p><blockquote>Интересный факт #3. В конце семидесятых годов в США была реальная угроза гиперинфляции: государство печатало деньги для стимуляции экономики, но производство только замедлялось. Тогда федеральный резерв США принял ряд мер направленных на достижение дефляции. Было сложно, кратковременно выросла безработица, многие бизнесы разорились, были протесты, но в течении пары лет экономика полностью реабилитировалась.</blockquote><h4>Кто виноват?</h4><p>Почему же все центральные банки так старательно избегают дефляции?<br> — Во-первых потому, что все государства погрязли в долгах.<br> — Во-вторых потому, что печатать деньги проще, чем увеличивать налоги.<br> — Во-третьих потому, что монетарные политики все-таки до какой-то степени эффективны для стимулирования (и регулирования) экономики (по крайней мере в краткосрочной перспективе).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*IXOYArOsUtpUH2WI.jpg" /><figcaption>Государственный долг США по сравнению с ВВП (<a href="https://www.forbes.com/sites/mikepatton/2015/02/26/when-and-why-government-debt-could-become-a-major-problem/">источник</a>)</figcaption></figure><p>По факту все конечно намного сложнее, но говоря очень грубо: с каждым новым напечатанным долларом (евро/рублем/франком) государства все больше загоняют себя в инфляционный тупик, из которого они сами уже не могут выбраться.</p><p>А при чем тут собственно биткоин? Он работает вне государств и центральных банков, его нельзя “напечатать”, ему все равно сколько у кого долгов. Биткоин предлагает альтернативу текущей системе.</p><p>Критика и комментарии приветствуются! Материал подготовлен для телеграм-канала <a href="https://t.me/cryptohodl">https://t.me/cryptohodl</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bef5aa4c596" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Practical solutions to inbound capacity problem in Lightning Network]]></title>
            <link>https://medium.com/lightningto-me/practical-solutions-to-inbound-capacity-problem-in-lightning-network-60224aa13393?source=rss-31fdaacddcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/60224aa13393</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[lightning-network]]></category>
            <dc:creator><![CDATA[Dmitry Laptev]]></dc:creator>
            <pubDate>Wed, 30 Jan 2019 10:30:34 GMT</pubDate>
            <atom:updated>2021-07-28T14:57:56.391Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Solutions to inbound</strong> liquidity problem in Lightning Network</h3><p>If you want to accept payments through lightning network or to properly balance your channels — your node needs to have sufficient <strong><em>inbound capacity</em></strong>. This article describes what that is and practical ways to get it.</p><blockquote>Update(July 2021): three years after it was written, this post is still mostly accurate, but some ways of getting inbound liquidity are missing or outdated. The services I mostly recommend nowadays are: lightning loop, lightning pool, lnbig.com, lightningnetwork.plus, t.me/theRingsOfFire and ln2me.com.</blockquote><h3>The problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6z2PRyJyXrFm6awsA4JgDA.png" /><figcaption>Toy network graph example. Left graph shows channels and its capacities — the information visible publicly. Right graph shows how the balances are actually distributed within each channel (unknown publicly) and directions funds can flow. From the picture on the left it may seem that node E has the best connectivity. But in practice all its balance is local, it has no inbound capacity, and can not receive or route payments.</figcaption></figure><p>Payments over <em>Lightning Network (LN)</em> work differently from how <em>on-chain</em> bitcoin transactions work. <a href="https://medium.com/lightningto-me/lightning-network-45b4b2119d97">My previous post</a> describes beautiful cryptographical magic behind LN, below are just few practical points.</p><ul><li>Lightning network consist of <em>two-sided channels</em>, and all the coins are locked in these channels.</li><li>The total amount of bitcoins locked in a channel is called <em>channel capacity</em>.</li><li>The amount on your side of the channel is called <em>local balance</em>. The amount on the side of the peer is called <em>remote balance</em>.</li><li>When you open a new channel — all your balance is local (here we omit <em>dual-funded channels</em> and <em>pushed amount</em> for simplicity).</li><li>The capacity of a channel always stays the same (here we omit <em>splicing</em> for simplicity) and roughly equals to your local balance plus the remote balance (roughly because of <em>commit fees</em>).</li><li>When you pay — the balance flows from your side of the channel to the remote side. When you receive payments — the other way around.</li></ul><p>Which brings us to one of the biggest culprits:</p><blockquote>In order to receive payments, your node needs to have sufficient <strong>inbound capacity</strong>: sufficient number of open channels with sufficient remote balance (otherwise the balance cannot flow to your side).</blockquote><p>To increase <em>inbound capacity</em> means to somehow get channels with large remote balance. And for small new nodes it can be very-very tricky. And if that is not enough, there is one more aspect to this:</p><blockquote>Not all inbound capacity is the same. It can be more useful or less useful. A channel from a well-connected and balanced node will connect your node to hundreds of other nodes. A channel from a new non-public node will not.</blockquote><p>Confused about how to get it right? Fear not, there are ways!</p><h3>Solution 1: Spend</h3><p>This is the obvious one, but it needs to be said. When you use a channel to spend coins, they are written off the local balance and added to the remote balance. The more you spend — the larger your remote balance, the more inbound capacity you have.</p><p>Of course this approach does not solve all the problems for everyone. But if you have a choice to pay via LN — use it and you will have less troubles with incoming payments in the future.</p><h3>Solution 2: Ask for incoming channels</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*lmkfaAs9APbq5pLIfEnYFw.jpeg" /></figure><p>This is probably the best option for most nodes: if you need inbound capacity — ask for incoming channels. If you are a merchant — ask your clients, if you know someone running a node — ask them.</p><p>But by far the easiest way is to use <em>channel opening services</em>. To the best of my knowledge — there are currently only three out there.</p><ol><li><a href="https://medium.com/@bitrefill/2d6ffbad3906">Thor</a> — a service by a lightning-enabled merchant <a href="https://www.bitrefill.com/">Bitrefill</a>. They can rent you a <em>private</em> channel with capacities from 0.003 and up to 0.16 BTC, which they promise to keep open for 30 days. Depending on the capacity it will cost you anywhere from a dollar and up to more than 20 bucks (update: the price is much higher nowadays).</li><li><a href="https://yalls.org/about/">Y’alls</a> — a service by <a href="https://twitter.com/alexbosworth">Alex Bosworth</a>, which allows you to pay less than a dollar for a 0.02 BTC channel (update: the price is much higher nowadays). And while this may seem cheaper than Bitrefill, beware that Y’alls sets higher than usual routing fees (which your clients will have to pay).</li><li><a href="http://lnbig.com/">LNBig.com</a> — a large liquidity provider that will sell a channel to your node for a reasonable fee.</li><li><a href="https://ln2me.com/">ln2me.com</a> (<a href="https://lightningto.me/">LightningTo.Me</a>) — my personal and non-profit hobby project that will establish a balanced channel of up to 0.1 BTC for free. And yes, it also sets very low routing fees.</li></ol><p>There are also nodes such as <a href="https://lightningpowerusers.com/home/">Lightning Power Users</a> that promise to open a channel to your node if you first open a channel to their node. Beware that this will not always work with nodes running <em>c-lightning</em>, which allows only one channel between two nodes.</p><p>(no longer working as of November 2020) Another interesting idea is a market place for channels. Two examples you can check are <a href="http://www.glowsat.com/#/">glowsat.com</a> and <a href="https://jolt.market/">jolt.market</a>. These services allow owners of LN nodes to buy and sell channels.</p><h3>Solution 3: Custodial exchange lightning bitcoins to on-chain bitcoins</h3><p>This may seem ridiculous to some, but that is actually a thing: you can exchange bitcoins for bitcoins. In a way, this is also a form of spending: you spend lightning bitcoins and buy on-chain bitcoins.</p><p>I hope that soon enough many large exchanges will enable lightning deposits, but for the moment there are not so many options. I will just mention some links: <a href="https://ln.bitfinex.com/">bitfinex.com</a>, <a href="https://zigzag.io/">zigzag.io</a>, <a href="https://fixedfloat.com/">fixedfloat.com</a>, <a href="https://sideshift.ai/">sideshift.ai</a>, <a href="https://hodlhodl.com/">hodlhodl.com</a>, <a href="https://www.southxchange.com/">southxchange.com</a>, <a href="https://www.btcduke.com/?lang=en">btcduke.com</a>, <a href="https://www.coinplaza.it/">coinplaza.it</a>, <a href="https://ln.zone/">ln.zone</a>, <a href="https://lightningconductor.net/invoice">lightningconductor.net</a>.</p><p>Please beware that exchange services are not always very reliable. Do your own research and immediately withdraw your coins once exchanged.</p><h3>Solution 4: LOOP and POOL</h3><p><strong>Loop by Lightning Labs.</strong> Similarly to the previous solution, <em>inverse submarine swaps</em> implement an exchange from lightning (off-chain) bitcoin to on-chain bitcoin. But this solution is better than the previous one, because it is non-custodial (does not require trust). It is currently not very user-friendly and more oriented towards developers, so I will just mention it briefly here. Please refer to <a href="https://blog.lightning.engineering/posts/2019/03/20/loop.html">the intro blog post</a> or go directly to <a href="https://github.com/lightninglabs/loop">the github repository</a>.</p><p><strong>Pool by Lightning Labs.</strong> This is a non-castodial marketplace for users willing to sell and buy liquidity. Also not very user-friendly for the moment, but please refer to <a href="https://lightning.engineering/posts/2020-11-02-lightning-pool/">the intro blog post</a> and <a href="https://github.com/lightninglabs/pool">the github repository</a>.</p><h3>Solution 5: Use custodial storage</h3><p>This is an even more dangerous way, because it requires you to trust a service for a long period of time. Doing your own research here is even more important than in the previous case. Essentially, these services allow you to deposit your money into their custody and promise to give it back when you need it.</p><p>Examples include various custodial wallets: <a href="https://bluewallet.io/">BlueWallet</a>, <a href="https://www.walletofsatoshi.com/">Wallet of Satoshi</a> or <a href="https://bitlum.io/">Bitlum</a>. For these everything is quite clear: you deposit lightning bitcoins from your node to theirs, freeing up local balance of your node.</p><p>But if you are creative enough, you can also make use of other services. For example, you can send yourself a large tip via <a href="https://tippin.me/">tippin.me</a>. This way you will store some portion of your funds on their node.</p><h3>Solution 6: Keep your node online</h3><p>If you simply keep your node always online— you will most probably get some incoming capacity. Open channels to random well-maintained nodes (I would appreciate if <a href="https://1ml.com/node/03bb88ccc444534da7b5b64b4f7b15e1eccb18e102db0e400d4b9cfe93763aa26d">my node</a> will be one of them), make sure that your node is publicly advertising its IP address, check that the ports are open, and setup monitoring to ensure that LN software is running 24/7.</p><p>First, people like nodes with at least some connectivity that are always online, because these nodes are more likely to root their payments. Second, some nodes are running on <em>autopilot</em>, and if you are online — you may get a channel from these nodes just by pure chance.</p><h3>Conclusion</h3><p>Accepting Lightning payments is trickier than accepting on-chain payments, but do not be discouraged, use some of the tips above. When your node matures — it will not be a problem at all.</p><p>Do you have any comments? Did I forget something? Please do not hesitate to share your thoughts! Let’s keep improving this post and help Lightning grow. Oh, and follow LightningTo.Me updates on <a href="https://twitter.com/LightningTo_Me">twitter</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60224aa13393" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lightningto-me/practical-solutions-to-inbound-capacity-problem-in-lightning-network-60224aa13393">Practical solutions to inbound capacity problem in Lightning Network</a> was originally published in <a href="https://medium.com/lightningto-me">LightningTo.Me</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zurich Street Art]]></title>
            <link>https://x0100.medium.com/zurich-street-art-65b0a6b4bdc4?source=rss-31fdaacddcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/65b0a6b4bdc4</guid>
            <category><![CDATA[photos]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[street-art]]></category>
            <category><![CDATA[zurich]]></category>
            <category><![CDATA[walking]]></category>
            <dc:creator><![CDATA[Dmitry Laptev]]></dc:creator>
            <pubDate>Wed, 05 Dec 2018 20:50:10 GMT</pubDate>
            <atom:updated>2021-05-12T12:51:14.225Z</atom:updated>
            <content:encoded><![CDATA[<p>If you think that urban art in Zurich is limited to a couple of places like Rote Fabrik and Oberer Letten, you are missing out on a huge part of the city culture. Just have a look at this map (it takes a while to load):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.google.com%2Fmaps%2Fd%2Fembed%3Fmid%3D1ovhIPtbex0xjHaUaowO5dU698mlMgFWg%26hl%3Den_US&amp;url=https%3A%2F%2Fwww.google.com%2Fmaps%2Fd%2Fviewer%3Fmid%3D1ovhIPtbex0xjHaUaowO5dU698mlMgFWg%26hl%3Den_US&amp;image=https%3A%2F%2Fwww.google.com%2Fmaps%2Fd%2Fthumbnail%3Fmid%3D1ovhIPtbex0xjHaUaowO5dU698mlMgFWg%26hl%3Den_US&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=google" width="600" height="450" frameborder="0" scrolling="no"><a href="https://medium.com/media/a052c5a100f4e3651f2b3c5c02261e4c/href">https://medium.com/media/a052c5a100f4e3651f2b3c5c02261e4c/href</a></iframe><p>And here is also the photo album for easier scrolling (photos are geotagged and you can join the album to stay updated):</p><p><a href="https://photos.app.goo.gl/k6HSkE1YAPHbYCPS8">Zurich street art</a></p><p>We started looking for street art as a way to enliven our walks. Turns out it is much more exciting than I thought it would be. It is fun and <em>(I would even dare to say)</em> educational, but it is also a great way to explore the city. Bonus: it can be done with a stroller :)</p><p>To the best of my knowledge this is the only (or at least the most comprehensive) map of Zurich street art pieces. You can <a href="https://www.google.com/maps/d/viewer?mid=1ovhIPtbex0xjHaUaowO5dU698mlMgFWg&amp;usp=sharing">add the map</a> to your phone and enjoy the exploration (or <a href="https://photos.app.goo.gl/k6HSkE1YAPHbYCPS8">join at the album</a> first to find something you like). If you want some pointers to get you started — please read further for my personal highlights:</p><ul><li>legal walls of Zurich,</li><li>massive murals by One Truth,</li><li>volumetric art by Redl,</li><li>world-famous stencils by C215,</li><li>playground by various local artists and kids,</li><li>squat building at Kernstrasse 14.</li></ul><p>Also check out <a href="http://drorhadadi.com/graffiti-and-street-art-in-zurich/">this great blog post</a> by Dror Hadadi from Tel Aviv!</p><h4>Legal walls of Zurich</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aAX8p9GFAuAFZ2bRaPdCnw.jpeg" /></figure><p>Ok, this one is obvious, but it needs to be said. There are multiple areas in Zurich open for artists to try their skills.</p><p>If you walk around <a href="https://rotefabrik.ch/">Rote Fabrik </a>and further along the lake, you can see tons of works by both beginners and experienced artists, sometimes sprayed one over another. This often looks like a mess, but it also makes the scene very dynamic and alive.</p><p>Other large area for legal street art is along the Limmat, close to Oberer Letten. There are also various temporary walls, usually along some construction sites.</p><h4>Massive murals by One Truth</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3vApRs1fChjIBcKkxyYiIg.jpeg" /></figure><p><a href="http://www.onetruth.ch/">One Truth</a> is one of the most prominent studios in Zurich, you can find their works all over the city, here is just a sneak peak.</p><p>Probably the most famous work by One Truth is spread over more than 10 walls. You can find it at Rötelstrasse 98, not far from Bucheggplatz.</p><p>The highest mural in Switzerland (over 20 meters, 8-story building) is at Wehntalerstrasse 312 in Affoltern.</p><p>My personal highlight is a very-very long millipede (70 meters) in the <a href="https://goo.gl/maps/KTRC6CqJFzN2">end of Sihlpromenade</a> (close to Bederstrasse). Update October 2020: this particular piece was replaced by <a href="https://www.instagram.com/p/CFP3qpUpPb3/">“Dog Heaven”</a>.</p><h4>Volumetric art by Redl</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*geoLOR4QqJGPcpr8F-D6gQ.jpeg" /></figure><p><a href="https://www.redl.ch/">Patrick Redl Wehrli</a> is one of my favorite artists based in Zurich. He is a master of fine details, bright colors and realistic shadows. Many of his works play with perspectives and look differently depending on where you stand.</p><p>Check out large and beautiful mural called “Melody” at Limmatstrasse 291. Or a very colorful girl with a lizard at Schaffhauserplatz. Or another girl with a dragonfly at Fischers Fritz. Or futuristic animals at Neugasse 81. Or a work that is all about your point of view at Badenerstrasse 141.</p><h4>World-famous stencils by C215</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1DbBlJS0KTlba1xntYam3w.jpeg" /></figure><p><a href="https://www.instagram.com/christianguemy/">C215 (Christian Guémy)</a> is a very famous french artist. I mean like almost Banksy-level famous. His paintings are all over the world, including Zurich.</p><p>We have managed to find two large pieces by him. The first one is the cat at Brauerstrasse 126. The second one is a beautiful stencil of a mother holding a child at Köchlistrasse 19.</p><p>There are also lots of small pieces on various post boxes. You can find at least four in the neighborhood of park Bäckeranlage.</p><p>By the way, Brauerstrasse 126 is also a home to <a href="http://starkart.org/">Starkart Urban Art Gallery</a>. They hold various street art exhibitions, and some of the works are publicly displayed on the house itself. Definitely worth checking out.</p><h4>Playground by various local artists and kids</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bLncc9XH6pfTHBwtkrcnw.jpeg" /></figure><p>This playground is well hidden in one of the courtyards in the city center. The entrance is right next to Josefstrasse 42.</p><p>It was sprayed by various local artists: <a href="https://www.instagram.com/elfkunst/">ELF</a>, <a href="https://www.instagram.com/tainagram/">Taina Thoma</a>, <a href="https://www.instagram.com/eulenheulen/">Eulen Heulen</a> and probably others I missed. According to <a href="https://www.instagram.com/p/BpCf_VMFP8H/">Street Art Archive instagram</a>, it was done with help from kids, which makes it even more fun to explore.</p><h4>Squat at Kernstrasse 14</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZc6HSFIm_l5-3-avUI2Fw.jpeg" /></figure><p><a href="https://kernstr14.noblogs.org/">Kernstrasse 14</a> is a very interesting building. One could call it a squat, but the website describes this place as a “self-organized social meeting point”.</p><p>People organize various activities in this building: theater, reading, open presentations, dancing, martial arts lessons and even cooking.</p><p>But more interesting part is purely ideological. This place is all against repression and isolation, against exploitation and borders, against sexism, racism and authoritarianism.</p><p>This ideology is perfectly represented by the art pieces on the walls of this building. The works there are not signed, and probably only few people know the authors, but it does not make the works themselves less appealing.</p><p>Another squat with some notable street art is <a href="http://www.kochareal.ch/">Kochareal</a> on Rautistrasse 22.</p><h4>Bonus: probably the oldest piece in Zurich</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OyiNLvOvj1AIktp94Kg2oQ.jpeg" /></figure><p>This street art was sprayed in 1978 on the walls of University of Zurich. This piece is called “Undine”, or a “Mermaid” — a work by a controversial artist <a href="https://en.wikipedia.org/wiki/Harald_Naegeli">Harald Naegeli</a>.</p><p>The story of the artist also known as a “Sprayer of Zurich” is fascinating. He was sentenced to nine months in jail and a fine of CHF 206,000 for his work. He fled to Germany, was evicted, served his jail sentence, but later was recognized by Swiss authorities and was rehabilitated.</p><p>You can find his works all over the city, some pieces are from eighties, and some are bright new.</p><h4>P.S.</h4><p>Street art is cool, because it is very dynamic, vivid and often surprising. I am pretty sure I missed lots of great spots. If you want to share your favorite pieces, contribute to the map, or just have questions — please write in the comments or reach out directly to me via <em>d@laptev.ch</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65b0a6b4bdc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lightning Network ⚡]]></title>
            <link>https://medium.com/lightningto-me/lightning-network-45b4b2119d97?source=rss-31fdaacddcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/45b4b2119d97</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[litecoin]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[lightning-network]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Dmitry Laptev]]></dc:creator>
            <pubDate>Tue, 30 Jan 2018 07:53:06 GMT</pubDate>
            <atom:updated>2018-10-15T19:18:54.914Z</atom:updated>
            <content:encoded><![CDATA[<p>Explained in (relatively) plain English.</p><p>First, we discuss why we need it (part 0) and describe an idea of payment channels and Lightning Network (part 1). Then we introduce required building blocks (part 2) and see how these blocks can be used to create payment channels (part 3). We then finally build Lightning Network, discuss its properties (part 4), and sum it all up (part 5).</p><blockquote>Disclaimer. I consciously omit/simplify some of the technical details. And also I am not an expert, and can be simply wrong.</blockquote><h3>0. Why?</h3><p>Bitcoin blockchain is a kind of decentralized database that stores every bitcoin transaction ever made. Here “every transaction ever” is a fundamental part of the protocol design. For system to be truly distributed and to prevent any mistakes, thousands of network nodes need to constantly double check each other and to record all the transactions.</p><p>Of course, this does not help scalability <em>at all</em>. Blockchain requires tens of gigabytes of hard drive storage, blocks are full, fees are rising, people are angry and fork bitcoin. Because of all that, alternative solutions are currently being developed. And one of these solutions is <em>Lightning Network (LN)</em>.</p><h3>Jameson Lopp on Twitter</h3><p>Q: When will the Lightning Network be rolled out? A: The rollout has already begun. This is an iterative distributed learning process; it&#39;s unlikely there will be a single point in time at which we say LN is &quot;deployed&quot; because it will grow organically. Software is never finished.</p><h3>1. Idea</h3><p>The idea of the <em>Lightning Network</em>, which belongs to a broader set of <em>second layer solutions</em>, is actually quite simple.</p><blockquote><strong><em>💡 </em></strong>Instead of storing and verifying all the transactions in the blockchain, let’s conduct most of the transactions “off-chain”. The main blockchain will mostly be used to synchronise the balances from time to time and to resolve conflicts. And as usual, this will all work using cryptomagic.</blockquote><p>This sounds intriguing, but absolutely unclear <em>how</em>…</p><h4>1.1. Payment channel</h4><p>Let’s start with simplifying the lives of two people (Alice and Bob), who often transact between each other. The following scheme is proposed.</p><ol><li>Alice and Bob send deposits to a special address. This address is jointly controlled by both of them using their two private keys.</li><li>Both Alice and Bob create a special <em>smart contract transaction</em> (yes, there are smart contracts in bitcoin, but more about that in the next part). This transaction is valid, but not yet recorded in the blockchain.</li><li>At first, the transaction contains information that Alice and Bob can get their deposits back.</li><li>When Alice is paying to Bob, they both by mutual agreement update the information in these transactions. Alice agrees to get less than her initial deposit, Bob — more. One can say for the sake of analogy that they are exchanging debt acknowledging documents (<em>IOU, I owe you</em>). But unlike most IOUs issued by banks, LN payments are fully secured and guaranteed to be immediately redeemable.</li><li>Like this, they can exchange small amounts (within the limits of their deposits) with each other, for as long as they both want.</li><li>At any moment in time any party can decide to square their balances. Then Alice (or Bob) just records the final version of their transaction to the main blockchain and they both get their deposits back (taking into account all the intermediate payments).</li></ol><p>Points 1–3 in these plan are called <em>opening the payment channel</em>. Points 4 and 5 — <em>using the channels. </em>Point 6 — <em>closing the payment channel</em>.</p><blockquote><strong><em>👍 </em></strong>Only two transactions are recorded in the main blockchain: sending the initial deposits (to open the channel), and the final transaction (to close the channel). All the intermediate payments are conducted without blockchain synchronisation. This makes payments within channels free and instant.</blockquote><h4>1.2. Network of payment channels</h4><p>Payment channels between two people <em>per se</em> are not super useful. Ultimately, we do not transact regularly with most people. But…</p><blockquote><strong><em>💡 </em></strong>When multiple payment channels form a network, any two people in this network can transact between each other. If there is a path between two nodes in the network, they can pay each other, even if they are not directly connected. This is the main idea of Lightning Network.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYgP4rEOttWssox5l-LGig.png" /><figcaption>Mainnet LN: the graph of payment channels as of 22.01.2018 (<a href="https://lnmainnet.gaben.win/">https://lnmainnet.gaben.win</a>).</figcaption></figure><p>Basically, analogous to TCP protocol, most people will need to have only one open channel to transact with anyone else.</p><p>Of course, there are many open questions left: how to find a path between two people, and how to motivate nodes to process payments. But let’s start with the main issue: the problem of trust.</p><h4>1.3. The problem of trust</h4><p>As it often happens in cryptography, the system of payment channels is easy to imagine when all the parties trust each other. There is no need in deposits, keys, special transactions. We can all just write down who owns whom and how much.</p><p>The question is: how to implement a payment channel and a network of payments channels <em>without trust</em>. There are going to be three main issues.</p><ol><li>Both Alice and Bob store their deposit in a joined wallet. If Bob refuses to sign transactions, then how will Alice ever return her deposit?</li><li>When transacting over the payment channel, Alice and Bob create many versions of IOU transactions. Assume Alice is mostly paying Bob. Then in the last version of the transaction Bob should receive more than his deposit. But Alice can cheat and submit the very first valid transaction, pretending that she never owed Bob anything. What shall Bob do in this case?</li><li>Assume Alice is paying Bob through Victor in the network of payment channels. How can they be sure that Victor will indeed pass the money, and not just steal it?</li></ol><p>We will call these issues, respectively: <em>“the problem of a joined deposit”</em>, <em>“the problem of the last transaction”</em> and <em>“the problem of intermediary”</em>.</p><p>All of the mentioned issues can actually be resolved using only a couple of tricks. But let’s not get ahead of ourselves. First, we will introduce some required building blocks…</p><h3>2. Smart contracts</h3><p>Bitcoin supports a simple smart contract programming language, called <a href="https://en.bitcoin.it/wiki/Script"><em>Script</em></a>. Every bitcoin transaction has a special field that contains a small script in this language. This script checks under which conditions the output of the transaction can be spend.</p><p><em>“To spend the output of transaction A” </em>is in fact just a more technically correct way of saying “to spend bitcoins from address/wallet <em>K</em>, to which these bitcoins were delivered using transaction <em>A</em>”.</p><blockquote><strong><em>☝ </em></strong>In comparison with ethereum, capabilities of smart contract in bitcoin are much more limited. This is because of the fact that Script is not a Turing-complete language. E.g. Script does not allow cycles/recursion, and does not allow creating variables (there is no memory).</blockquote><p>See the the link below to read a bit more about transactions structure and using scripts.</p><p><a href="https://medium.com/@x0100/bitcoin-transactions-malleability-segwit-and-scaling-258af8ed9cbf">Bitcoin: transactions, malleability, SegWit and scaling</a></p><p>Let’s have a look at a couple of important operations of bitcoin scripts.</p><h4>2.1. Authorisation</h4><p>Perhaps the most standard part of every transaction is <em>signature verification</em>. Let transaction <em>A</em> fund some address <em>K </em>with some number of bitcoins. In order to later spend these bitcoins from <em>K</em>, one needs to prove that they have the key. This is checked using operation OP_CheckSig.</p><p>But we can additionally check something else. For example, we can check that a person has a secret number, the hash of which is equal to the given value. For that we need two operations: OP_SHA256 (computes the hash of the provided parameter) and OP_EqualVerify (checks equality). In part 4 we will discuss why would anyone need that.</p><h4>2.2. Cooperation</h4><p>Another common example of simple bitcoin smart contracts is based on the operation OP_CheckMultiSig. This operation allows to spend funds from an address only when signed with multiple keys.</p><p>This principle is used for so-called <em>multiple signature</em> (<em>multisig</em>) wallets. It works approximately like a bank deposit box closed with two locks. One key belongs to a client, the second one — to an employee of the bank.</p><h4>2.3. Timing</h4><p>Since quite recently bitcoin also supports an operation called OP_CheckSequenceVerify, which allows to spend the funds only after some fixed number of blocks.</p><p>For example, this can be used to discipline people unable to save money. Blockchain works better than any piggy bank: if someone decides to freeze the savings for some time, the money will be securely frozen.</p><p>But beyond this scenario, OP_CheckSequenceVerify and other components are actively used for payment channel implementation.</p><h3>3. Payment channel implementation</h3><p>Now with all the building blocks ready, we can describe how payment channels actually work.</p><p>In reality, there exists a <a href="https://en.bitcoin.it/wiki/Payment_channels">whole variety</a> of different payment channels, and the first one was proposed by Satoshi him/her/them-self. We will <em>approximately</em> follow the specification called <em>Poon-Dryja payment channels</em> (named after the two authors of <a href="https://lightning.network/lightning-network-paper.pdf">the Lightning Network paper</a>).</p><h4>3.1. Opening the channel</h4><ol><li>Alice and Bob create a transaction/transactions transferring their money to a joined deposit address <em>O</em>. Assume that Alice transfers <em>X</em> bitcoins from her wallet, Bob transfers <em>Y</em> bitcoins. The funds from this joined deposit can only be spent when signed with two keys from Alice and Bob (OP_CheckMultiSig).</li><li>The first trick is that they do <em>NOT</em> yet sign the transaction and do <em>NOT</em> yet submit this transaction to the blockchain. Otherwise Bob can refuse to cooperate and Alice will lose access to her money forever.</li><li>Instead, Alice and Bob create two new refund transactions (<em>A1</em> and <em>B1</em> respectively). The input of these transactions is the money from the joint account (the output of transaction <em>O</em>). There are two outputs: <em>X</em> bitcoins is to be transferred back to Alice, and <em>Y</em> — back to Bob. <em>In reality everything is a bit more complicated, but we’ll discuss it later.</em></li><li>Then Bob signs the transaction <em>A1</em> and gives it to Alice. Alice signs the transaction <em>B1</em> and gives it to Bob.</li><li>And now the initial deposit transaction <em>O</em> can be safely recorded in the main blockchain. No one is going to freeze anyones money. If Bob refuses to cooperate, Alice will just sign her transaction <em>A1</em>, record it in the blockchain and will return her deposit.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*EOMAUYdJbLaEPq2OPhPMJQ.png" /><figcaption>Deposit refund transactions.</figcaption></figure><p>Now <em>“the problem of a joint deposit”</em> is solved. The channel can be opened without any trust to the second party.</p><blockquote><strong><em>☝</em></strong><em> An interesting fact.</em> Just half a year ago (before the SegWit activation) signing an output of an unconfirmed transaction (point 4 above) was much harder, because of <a href="https://medium.com/@x0100/c581ece107ba">transaction malleability problem</a>.</blockquote><h4>3.2. Using the channel</h4><p>Payments within a channel are in fact implemented by rewriting transactions <em>A1</em> and <em>B1</em> with the new transactions.</p><ol><li>Alice is paying Bob for a cup of coffee that costs <em>C</em>.</li><li>Alice agrees that when closing the channel, she will receive not the original amount <em>X</em>, but <em>X’=(X-C)</em>.</li><li>Bob agrees to receive <em>Y’=(Y+C)</em>.</li></ol><p>New transactions <em>A2</em> and <em>B2</em> will look exactly the same as <em>A1</em> and <em>B1</em>, but with new amounts. Any party can close the payment channel at any time, submitting the last version of the transaction to the blockchain.</p><p>How to make sure that Alice will not submit transaction <em>A1</em> instead of transaction <em>A2</em>? This is solved with the second trick.</p><ol><li>Every time Alice and Bob create new transactions, they also select a <em>one-time private key</em>. This key can be used by one party to collect the deposit of another party (OP_CheckSig).</li><li>With every new payment <em>i</em>, Alice is revealing to Bob her previous private key <em>AK(i-1)</em> and creates a new key <em>AKi</em>. Bob does not accept payment without the previous key.</li><li>If Bob knows Alice’s key, he can spend all the Alice’s money. But only if Alice decides to record an incorrect transaction to the blockchain.</li><li>This scheme insures that Alice is always motivated to record only the last transaction to the blockchain.</li></ol><p><em>Last small modification.</em> To dispute the transaction Alice submits to the blockchain and to provide her key, Bob needs time. Because of that Alice is not going to get her deposit immediately after she closes the channel, but after some number of blocks T (OP_CheckSequenceVerify). For example, she may need to wait for 48 blocks, which is approximately 8 hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*y-nHNUy-ppCgA-vxPOjgdA.png" /><figcaption>The final form of the transactions used for a payment channel.</figcaption></figure><p>If Alice signs one of her transactions (they are already signed by Bob) and submits this transaction to the blockchain, two scenarios are possible.</p><ol><li>Alice submits her last transaction =&gt; Bob does not know the last private key <em>AKi</em>. This is a valid closure of the channel, everyone should get their unspent money. Alice will get hers after some time.</li><li>Alice is trying to record her older transaction instead of the last one =&gt; she is trying to cheat. In this case Bob knows Alice’s key and he can use it to get all the Alice’s money. Obviously, Alice is not interested in this scenario.</li></ol><p>So, “<em>the problem of the last transaction</em>” is also solved. Payment channel between two people is ready. Now it also becomes clear, what are the advantages and disadvantages of using payment channels.</p><blockquote><strong><em>👍</em> Advantages:</strong> 1. payments are instant and free, they do not create a burden on the main blockchain. 2. two parties do not have to trust each other.</blockquote><blockquote><strong><em>👎</em> Disadvantages:</strong> 1. deposits are blocked for the whole time while the channel exists. 2. both parties should from time to time go online (at least once in <em>T </em>blocks).</blockquote><p><strong>👌</strong> In practice, both disadvantages are important for payment channels between two people, but much less important in the context of Lightning Network. First point stops being a disadvantage when one channel can be used to pay to various different people.</p><p>Second point is also basically non-existent in LN, because one can outsource correctness verification to a third party. If Bob is not online when Alice is closing the channel, and some random David discovers that Alice is cheating, then both Bob and David can split Alice’s confiscated deposit.</p><p>One more small note before we move further. You may think that operating a payment channel requires a lot of bookkeeping: tracking and signing different versions of transactions, exchanging signed these transactions and also temporary keys. And you will certainly be right. <em>Good news is: when properly implemented, this will be all happening behind the scenes</em>, the users will just send the money and receive them.</p><h3>4. Lightning Network</h3><h4>4.1. Payment channel though an intermediary</h4><p>Let’s now assume that Alice and Bob do not have a payment channel between each other, but both have an open channel with Victor. Alice can safely transfer money to Victor, Victor can safely transfer money to Bob.</p><p>But how to make sure that Victor, once he receives the money, will indeed pass them further to Bob?</p><p>The idea here is going to be quite similar to the previous trick. But instead of one-time private keys, they will use a secret number.</p><ol><li>When the payment is initiated, Bob selects a secret number <em>S</em>, computes a hash of this number <em>HS</em>, and transfers this information to Alice. <em>HS</em> can also be used as a virtual receipt.</li><li>Alice creates a transaction <em>AV</em> that transfers the money to Victor, but only in case Victor shows a secret number <em>S</em>. For that she uses a script checking the hash of the provided number and comparing it to the value of <em>HS </em>(this is where we need OP_SHA256 and OP_EqualVerify).</li><li>Victor is creating a similar transaction <em>VB</em> transferring money to Bob, but only if Bob provides a secret number <em>S</em>.</li><li>Bob sees that he will be able to get the money from Victor and shows him his secret number <em>S</em>.</li><li>Now Victor can prove to Alice he transferred the money and successfully receive transaction <em>AV</em>.</li></ol><p>There are couple of scenarios possible.</p><ol><li>First, it does not make sense for Victor to cheat. By design, if he does not pass the money to Bob, he will not get the money from Alice.</li><li>But Bob can decide to cheat and not to reveal the secret key to Victor. To get the money Bob will need to close the channel with Victor and to submit transaction <em>VB</em> to the blockchain. <em>But</em> to actually spend the money, Bob will need to show his secret number anyway. And as the blockchain is public, Victor will also see it.</li></ol><p>There is a couple of non-trivial technicalities with selecting the right timeframe for Alice, Victor and Bob to resolve possible conflicts. But these technicalities are way out of scope of this introductory article. If interested — google <em>Hash Time-Locked Contracts (HTLCs)</em>.</p><h4>4.2. Routing</h4><p>In practice Alice and Bob can be connected through any arbitrary number of unknown/anonymous intermediaries across the whole world. The problem of finding the most optimal path of intermediaries in a graph of network nodes is called a <em>routing problem</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*933GpxVj8PzBVPMQGbDeng.png" /><figcaption>Geographical distribution of bitcoin testnet nodes (<a href="https://explorer.acinq.co/#/">https://explorer.acinq.co/#/</a>).</figcaption></figure><p>The routing problem is in fact an area of active research at the moment. Optimal path depends on many dynamic factors: the availability of nodes, network topology, channels throughput, intermediaries fees.</p><p>Without going into too many details, finding the path and passing the payments in LN is currently done based on <a href="https://en.wikipedia.org/wiki/Onion_routing"><em>Onion routing</em></a><em> — </em>a technology for anonymous peer-to-peer routing, which is also used, for example, in <a href="https://www.torproject.org/">Tor</a>.</p><p>Everything is decentralized, the traffic is encrypted. No intermediary knows from whom the bitcoins come and where they go. One more advantage follows from this.</p><blockquote><strong><em>👍</em> Advantages:</strong> Lightning Network is much more anonymous than bitcoin itself. First, an absolute majority of the transactions are never recorded in a public ledger, these transactions are only visible to a handful of nodes. Second, even among the nodes involved in routing, only the first and the last node knows the source and the destination of the payment.</blockquote><h4>4.3. Fees economy</h4><p>Only two major questions left.</p><p><strong>Question number 1:</strong> why would an intermediary node process any payments from someone else?</p><p>First of all, because good connectivity allows them to use LN more efficiently. Second, because they receive fee: usually <em>very small</em>, but motivational enough.</p><p>At the moment the network is mostly supported by enthusiasts and the fees are almost zero: 1 satoshi, or ~0.01 <em>cents</em> for every intermediary node.</p><blockquote><strong><em>👍</em> </strong>The “bandwidth” of payment channels is a much less valuable resource than the block size. Channels are cheap and easy to open. Because of that fees in LN are orders of magnitude smaller than the fees in the main bitcoin blockchain.</blockquote><p><strong>Question number 2:</strong> and what about the miner fees payed on the main blockchain to open/close payment channels?</p><p>Indeed, these fees can be quite large, reaching sometimes tens of dollars. Therefore, payments are going to be cheaper if the channels are open/closed rarely.</p><p>This in turn motivates people to open channels with larger deposits, and to use channels bi-directionally: not only for outgoing payments, but also for incoming ones.</p><p><em>Example</em>: I open a channel and fund it with 1000 dollars to use it for only outgoing payments. The turnover in the channel over the lifetime will be exactly 1000 dollars, and I will pay ~20 dollars in fees to open and close the channel. This results in 2% fees. Slightly lower than visa and mastercard, but still not as low as I would like.</p><p>The situation changes dramatically when the I start using Lightning to the fullest: deposit larger amounts and also start receiving money through channels. Then, depending on the proportion of spent/received money, <em>the channel can be open forever and the fees will be converging to almost zero in the limit</em>.</p><h4>4.4. Criticism</h4><p>It is easy to find lots of criticism of second layer solutions in general and of Lightning Network in particular. Some points actually deserve attention, some are outdated myths. Here is a couple of examples.</p><blockquote>1. Using LN leads to centralization: users benefit from connecting to large hubs, and few of these hubs can control all the traffic.</blockquote><p>This is a valid concern and deserves attention, but the risks are not huge. First, it is economically profitable and very simple to run a new node bypassing large hubs. Second, routing algorithms should balance the traffic among all the possible paths. And third, at least for the moment we <a href="https://lnmainnet.gaben.win/">do not see this centralization happening</a>. Going forward, I hope the optimal topology is going to be encouraged by wallet software itself.</p><blockquote>2. Low channel throughput will result in LN congestion, fees rising, and the situation will be as bad as in the main bitcoin blockchain.</blockquote><p>Again, as soon as this starts happening, people will have larger economic incentives to run their own nodes. Unlike the block size, the number of nodes/channels is almost unlimited.</p><blockquote>3. Efficient and effective routing on large number of peer-to-peer nodes is impossible. Especially when accounting the cost of opening new channels.</blockquote><p>These problems are <em>far-far-far</em> into the future. But the research in this direction is already happening (<a href="http://bitfury.com/content/5-white-papers-research/whitepaper_flare_an_approach_to_routing_in_lightning_network_7_7_2016.pdf">example</a>). The community will come up with something.</p><blockquote>4. Channels need to be often opened and closed. Fees spent on that will be high, and LN will become more and more expensive.</blockquote><p>Actually, this is an outdated myth still circling around. Early proposals of payments channels indeed were uni-directional and could last only for a fixed time. Now these problems are both solved.</p><blockquote>5. You need to be online to use LN.</blockquote><p>Partly true. Unlike early LN implementations, there is no need to be always online: other participants can monitor my open channels and verify that no one is cheating. But you indeed need to be online to send/receive money. This is of course a limitation, but a much less significant one.</p><blockquote>6. LN is not compatible with cold storage.</blockquote><p>This is a very good point and valid concern. Funds locked in payment channels are controlled by the wallets being online (<em>hot wallets</em>). So additional security for nodes will be required to protect against hackers.</p><blockquote>7. LN transactions are not as safe as on-chain transactions.</blockquote><p>LN payments are indeed more risky than on-chain transactions. But only <a href="https://blog.bitmex.com/the-lightning-network/">in case of a successful 51% attack</a>. The risk of it is very-very small.</p><h3>5. LN today</h3><p>The most important thing you need to know: Lightning is already here and it really works.</p><p><a href="https://explorer.acinq.co/#/">More than a thousand nodes</a> in bitcoin testnet and <a href="https://lnmainnet.gaben.win/">more then three hundred nodes</a> (growing every day) in mainnet are already processing transactions and testing different software today.</p><h3>elizabeth stark on Twitter</h3><p>@TraceMayer @Blockstream @coinbase @BitPay @adam3us Bug testing should be on testnet, not mainnet. Especially when the devs are still losing money. 🙃 https://t.co/QYx94V0vpR</p><p>As for software, there are three main implementation: <a href="https://github.com/lightningnetwork/lnd">lnd</a> from <em>Lightning Labs</em>, <a href="https://github.com/ElementsProject/lightning">c-lightning</a> from <em>Blockstream</em>, <a href="https://github.com/ACINQ/eclair">eclair</a> from <em>ACINQ</em>. These teams have been working for years to create standard specifications for nodes interactions called <a href="https://github.com/lightningnetwork/lightning-rfc"><em>Lightning Network Specifications (BOLTs)</em></a>. And recently, in the end of 2016, they performed massive successful payment testing. All three implementations proved to be compatible.</p><p>At the moment, you can pay with real bitcoins using LN in only three or four online shops. But this is a whole three or four shops more than just a month ago, so this is already a great success 😊</p><p>Of course, the moment of ubiquitous transition from <em>on-chain</em> bitcoin payments to <em>off-chain</em> payments is still far away. A huge work should still be carried out by developers of wallets, payment gateways, exchanges, online stores. And, of course, by users themselves.</p><p>The most interesting in this story is that faster, cheaper and more anonymous transactions — is only the beginning of the story! Soon we will see even more anonymity, atomic swaps, decentralized exchanges and many more cool things. The future is exciting! ⚡</p><p><em>More technical details about LN: </em><a href="https://lightning.network/lightning-network-paper.pdf"><em>1</em></a><em>, </em><a href="https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki"><em>2</em></a><em>, </em><a href="https://github.com/lightningnetwork/lightning-rfc"><em>3</em></a><em>, </em><a href="https://github.com/ElementsProject/lightning/blob/master/doc/deployable-lightning.pdf"><em>4</em></a><em>, </em><a href="https://blog.bitmex.com/the-lightning-network/"><em>5</em></a><em>.</em></p><p><a href="https://medium.com/@x0100/7c618c9cd68">This article in Russian (статья на русском).</a></p><p>Please do comment, criticize, ask questions, subscribe. More about the author: <a href="http://laptev.ch/">http://laptev.ch</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45b4b2119d97" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lightningto-me/lightning-network-45b4b2119d97">Lightning Network ⚡🕸</a> was originally published in <a href="https://medium.com/lightningto-me">LightningTo.Me</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lightning Network ⚡]]></title>
            <link>https://x0100.medium.com/%EF%B8%8Flightning-network-7c618c9cd68?source=rss-31fdaacddcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c618c9cd68</guid>
            <category><![CDATA[блокчейн]]></category>
            <category><![CDATA[биткоин]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[lightning-network]]></category>
            <dc:creator><![CDATA[Dmitry Laptev]]></dc:creator>
            <pubDate>Fri, 26 Jan 2018 22:01:52 GMT</pubDate>
            <atom:updated>2018-02-05T22:19:44.600Z</atom:updated>
            <content:encoded><![CDATA[<p>Относительно простым русским языком.</p><p><a href="https://medium.com/@x0100/lightning-network-45b4b2119d97">Same article is also available in English.</a></p><p>В части 0 посмотрим, зачем это надо. В части 1 обсудим поверхностно общую идею платежных каналов, Lightning Network и проблемы. В части 2 введем необходимые строительные блоки. В части 3 наконец-то опишем более строго детали работы платежного канала. В части 4 по-быстрому построим Lightning из платежных каналов, расскажем про критику и комиссии. В части 5 немного подытожим.</p><blockquote>Дисклеймер. Я сознательно опускаю/упрощаю некоторые технические моменты. А еще я не эксперт, и могу банально ошибаться.</blockquote><h3>0. Зачем?</h3><p>Блокчейн биткоина — это своего рода децентрализованная база данных, в которой сохраняются все транзакции сети. При этом <em>“все транзакции”</em> — это довольно фундаментальная часть определения протокола. Чтобы система была по-настоящему децентрализованной и чтобы при этом не допустить ни одной ошибки, нужно, чтобы тысячи узлов сети перепроверяли и сохраняли все транзакции.</p><p>Это, разумеется, совсем не способствует масштабируемости: блокчейн занимает десятки гигабайт на диске, блоки переполнены, комиссии растут, люди ругаются и форкают биткоин. Поэтому в данный момент активно разрабатываются альтернативные решения. Одним из таких решений являются <em>Lightning Network (далее LN)</em>.</p><h3>Jameson Lopp on Twitter</h3><p>Q: When will the Lightning Network be rolled out? A: The rollout has already begun. This is an iterative distributed learning process; it&#39;s unlikely there will be a single point in time at which we say LN is &quot;deployed&quot; because it will grow organically. Software is never finished.</p><h3>1. Идея</h3><p>Идея решений второго уровня <em>(second layer solutions)</em>, к которым и относится <em>LN</em>, звучит довольно просто.</p><blockquote><strong><em>💡 </em></strong>Вместо того, чтобы записывать и верифицировать все транзакции на блокчейне, давайте будем проводить большую часть платежей вне сети (off-chain), а на главный блокчейн будем время от времени по желанию синхронизировать балансы и разрешать на нем конфликты. А работать это будет как всегда с помощью криптомагии.</blockquote><p>Звучит интригующе, но совсем непонятно <em>как</em>…</p><h4>1.1. Платежный канал</h4><p>Начнем с того, как можно упростить жизнь двум людям, Алисе и Бобу, которые часто расплачиваются между собой. Предлагается следующая схема.</p><ol><li>Алиса и Боб отправляют депозиты на адрес, который управляется ими совместно с помощью двух приватных ключей.</li><li>Каждый из них создает специальную транзакцию — смарт-контракт (да, в биткоине есть смарт-контракты, об этом в следующей части). Эта транзакция корректна, но пока не записывается в блокчейн.</li><li>Изначально транзакции содержат информацию о том, что Алиса и Боб могут забрать свои депозиты обратно.</li><li>Когда Алиса расплачивается с Бобом, они по обоюдному согласию обновляют информацию в этих транзакциях. Алиса соглашается получить меньше изначального депозита, Боб — больше. По сути эти транзакции представляют собой долговые обязательства (<em>IOU, I owe you</em>). Но в отличии от большинства банковских долговых обязательств, LN платежи 100% обеспечены и могут быть реализованы в любой момент.</li><li>Так они могут обмениваться небольшими суммами (в пределах их депозитов) друг с другом, хоть до бесконечности.</li><li>В какой-то момент любая сторона может решить рассчитаться окончательно. Тогда Алиса (или Боб) просто записывают одну финальную транзакцию в главный блокчейн и получают суммы депозитов с учетом всех промежуточных платежей.</li></ol><p>Пункты 1–3 в этой схеме называются открытием <em>платежного канала (payment channel, канал микроплатежей)</em>. Пункты 4 и 5 — использованием канала. Пункт 6—закрытием платежного канала.</p><blockquote><strong><em>👍 </em></strong>В блокчейн записывается всего две транзакции: перечисление депозитов для открытия канала и финальная транзакция (закрытие канала). Все промежуточные платежи осуществляются без синхронизации с блокчейном, поэтому проходят они бесплатно и мгновенно.</blockquote><h4>1.2. Сеть платежных каналов</h4><p>Сами по себе платежные каналы между двумя людьми — вещь не особо полезная. В конце концов, с большинством людей мы не проводим частых регулярных транзакций. Но…</p><blockquote><strong><em>💡 </em></strong>Когда платежные каналы выстраиваются в сеть, появляется возможность проводить платежи между любыми участниками, между которыми есть путь в графе этой сети (даже если они не связаны напрямую). Это и есть основная идея Lightning Network.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYgP4rEOttWssox5l-LGig.png" /><figcaption>Так выглядел граф платежных каналов на момент 22.01.2018 (<a href="https://lnmainnet.gaben.win/">https://lnmainnet.gaben.win</a>).</figcaption></figure><p>В принципе, аналогично протоколу TCP, простому человеку достаточно иметь всего один открытый канал, чтобы проводить транзакции с кем угодно.</p><p>Конечно, нужно еще искать оптимальные пути между двумя людьми, и еще нужно как-то мотивировать участников обрабатывать чужие платежи. Но начнем с основной проблемы: с проблемы доверия.</p><h4>1.3. Проблема доверия</h4><p>Как часто бывает в криптографии, систему платежных каналов легко себе представить, если все стороны доверяют друг другу. Нет необходимости городить огород с депозитами, ключами, специальными транзакциями. Можно просто записывать, кто кому сколько должен.</p><p>Дело за малым: понять, как можно реализовать канал платежей и сеть этих каналов <em>без доверия</em>. Основных проблем будет три.</p><ol><li>Оба депозита от Алисы и Боба хранятся на общем кошельке. Если Боб откажется подписывать транзакции, то как Алисе вернуть свой депозит?</li><li>В процессе расчетов создается много версий долговых обязательств. Предположим, что в основном Алиса платит Бобу. Тогда в финальной версии транзакции Боб получает больше своего депозита, а Алиса — меньше. Но Алиса может схитрить и самовольно записать в блокчейн самую первую валидную версию транзакции, как будто Боб никогда и не получал денег. Что тогда делать Бобу?</li><li>Если Алиса и Боб передают деньги по сети каналов через Витю, то как они могут убедиться, что Витя действительное передаст деньги, а не заберет их себе?</li></ol><p>Назовем эти проблемы соответственно: <em>“проблема общего депозита”, “проблема последней транзакции” и “проблема посредника”</em>.</p><p>Все перечисленные выше проблемы решаются с помощью буквально парочки трюков. Но обо всем по порядку: для начала введем несколько необходимых строительных блоков…</p><h3>2. Смарт-контракты</h3><p>Биткоин поддерживает простейший <a href="https://en.bitcoin.it/wiki/Script">язык смарт-контрактов <em>Script</em></a>. В каждой биткоин-транзакции есть специальное поле, которое содержит скрипт на этом языке. Этот скрипт проверяет, при выполнении каких условий выход транзакции может быть потрачен.</p><p><em>“Потратить выход транзакции A”</em> — это на самом деле более технически корректный способ сказать “потратить деньги с адреса/кошелька <em>K</em>, на который они были зачислены с помощью транзакции <em>A</em>”.</p><blockquote><strong><em>☝ </em></strong>В отличии, например, от этереума, возможности смарт-контрактов биткоина намного более ограничены. Связано это с тем, что Script не является полным по Тьюрингу. Например, в нем нельзя использовать циклы/рекурсию и нельзя создавать переменные (отсутствует память).</blockquote><p>Про устройство транзакций и использование скриптов можно почитать по ссылке ниже.</p><p><a href="https://medium.com/@x0100/%D0%B1%D0%B8%D1%82%D0%BA%D0%BE%D0%B8%D0%BD-%D1%82%D1%80%D0%B0%D0%BD%D0%B7%D0%B0%D0%BA%D1%86%D0%B8%D0%B8-%D0%BF%D0%BB%D0%B0%D1%81%D1%82%D0%B8%D1%87%D0%BD%D0%BE%D1%81%D1%82%D1%8C-segwit-%D0%B8-%D0%BC%D0%B0%D1%81%D1%88%D1%82%D0%B0%D0%B1%D0%B8%D1%80%D1%83%D0%B5%D0%BC%D0%BE%D1%81%D1%82%D1%8C-c581ece107ba">Биткоин: транзакции, пластичность, SegWit и масштабируемость</a></p><p>Рассмотрим несколько важных операций этого языка.</p><h4><strong>2.1. Авторизация</strong></h4><p>Пожалуй, самая стандартная часть любой транзакции — это проверка подписи. Пусть транзакция <em>A</em> зачисляет средства на некий адрес <em>K. </em>Чтобы дальше потратить деньги с <em>K</em>, нужно доказать наличие ключа. За это отвечает операция OP_CheckSig.</p><p>Но при желании, можно также проверить что-нибудь дополнительное. Например, можно проверить, что у человека есть секретное число, хеш от которого равен заданному значению. Для этого нужно две операции: OP_SHA256 (считает хэш) и OP_EqualVerify (проверяет равенство). Зачем это нужно станет понятно в части 4.</p><h4><strong>2.2. Кооперация</strong></h4><p>Другой пример простейших смарт-контрактов на биткоине основан на операции OP_CheckMultiSig. Она позволяет тратить средства только при подписании несколькими определенными ключами.</p><p>На этом принципе построены так называемые <em>multiple signature</em> кошельки. Примерно как ячейка в банке, которая закрывается на два замка (один ключ у работника банка, второй — у клиента).</p><h4><strong>2.3. Сроки</strong></h4><p>С относительно недавних пор биткоин также поддерживает операцию OP_CheckSequenceVerify, которая позволяет тратить средства только через какое-то фиксированное количество блоков.</p><p>Например, это позволяет дисциплинировать людей, которые не умеют откладывать деньги. Блокчейн работает лучше любой копилки: если пользователь решил заморозить сбережения на какой-то срок, то они будут гарантировано заморожены.</p><p>Но помимо этого сценария, OP_CheckSequenceVerify и другие компоненты активно используются в реализации платежного канала.</p><h3>3. Реализация канала</h3><p>Теперь, когда все строительные блоки на месте, можно описать некоторые детали работы платежного канала.</p><p>На самом деле разновидностей платежных каналов <a href="https://en.bitcoin.it/wiki/Payment_channels">довольно много</a>, и первую из них предложил еще Сатоши. Я буду <em>примерно</em> ориентироваться на спецификацию, которая называется <em>Poon-Dryja payment channels</em> (по имени главных авторов <a href="https://lightning.network/lightning-network-paper.pdf">статьи про Lightning Network</a>).</p><h4><strong>3.1. Открытие канала</strong></h4><ol><li>Алиса и Боб создают транзакцию/транзакции, которые зачисляют средства на общий адрес-депозит <em>O</em>. Предположим, что <em>X</em> биткоинов зачисляется с кошелька Алисы и <em>Y — </em>с кошелька Боба. Средства с общего депозита можно потратить только при подписании одновременно ключами Алисы и Боба (OP_CheckMultiSig).</li><li>Первый трюк заключается в том, что они пока <em>НЕ </em>подписывают и<em> НЕ </em>транслируют созданную транзакцию в блокчейн (иначе Боб может обмануть Алису и заморозить её средства навечно).</li><li>Вместо этого Алиса и Боб создают две новые транзакции возвращения депозитов (соответственно <em>A1</em> и <em>B1</em>). Входом этих транзакций являются средства с общего депозита (выход транзакции <em>O</em>). Выходов у транзакций два: <em>X</em> уйдет обратно на адрес Алисе, <em>Y</em> — Бобу. <em>На самом деле все немного сложнее, но об это чуть позже.</em></li><li>Дальше Боб подписывает транзакцию <em>A1</em> и передает её Алисе. Алиса подписывает транзакцию <em>B1</em> и передает её Бобу.</li><li>Теперь транзакцию зачисления депозитов можно смело транслировать в блокчейн, никто никого не обманет. Если Боб откажется кооперировать, Алиса всегда сможет подписать транзакцию <em>A1</em>, записать её в блокчейн и вернуть свой депозит.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*aZNpk7u9-vHxGL0lSeQKGA.png" /><figcaption>Транзакции возвращения депозитов.</figcaption></figure><p>Теперь <em>“проблема общего депозита”</em> решена. Открытие канала можно провести без доверия второй стороне.</p><blockquote><strong><em>☝</em></strong><em> Интересный факт.</em> Еще полгода назад (до внедрения SegWit) подписание выхода неподтвержденной транзакции (пункт 4) провернуть было намного сложнее из-за проблемы <a href="https://medium.com/@x0100/c581ece107ba">пластичности транзакций (transaction malleability)</a>.</blockquote><h4><strong>3.2. Использование канала</strong></h4><p>Платежи внутри канала на самом деле осуществляются переписыванием транзакций <em>A1</em> и <em>B1</em> на новые транзакции.</p><ol><li>Алиса платит Бобу за кружку кофе, которая стоит <em>C</em>.</li><li>При этом Алиса соглашается, что при закрытии канала она заберет не изначальную сумму <em>X, </em>а <em>X’=(X-C)</em>.</li><li>Боб при этом получит <em>Y’=(Y+C)</em>.</li></ol><p>Соответственно, новые транзакции <em>A2</em> и <em>B2</em> будут выглядеть точно также, как <em>A1</em> и <em>B1</em>, но с новыми суммами. Любая из сторон может в любой момент закрыть канал, записав последнюю версию транзакции в блокчейн.</p><p>Как убедиться, что Алиса не запишет в блокчейн транзакцию <em>A1</em> вместо транзакции <em>A2</em>? Для этого есть еще один трюк.</p><ol><li>Каждый раз, когда Алиса и Боб создают новые транзакции, они выбирают <em>одноразовый приватный ключ</em>, который нужен, чтобы забрать депозит (OP_CheckSig).</li><li>При каждом очередном платеже <em>i</em>, Алиса показывает Бобу предыдущий приватный ключ <em>AK(i-1)</em>, и создает новый ключ <em>AKi</em> для новой транзакции. Боб не принимает оплату без предыдущего ключа.</li><li>Если Боб знает ключ, то он может потратить все деньги Алисы. Но только в случае, если Алиса решит записать неправильную транзакцию в блокчейн.</li><li>Таким образом, Алиса всегда заинтересована в том, чтобы записывать в блокчейн только самую последнюю транзакцию.</li></ol><p><em>Последняя маленькая модификация.</em> Для того, чтобы у Боба была возможность оспорить транзакцию Алисы и предоставить её ключ, Бобу нужно время. Поэтому Алиса будет получать свой депозит не сразу, а через какое-то количество блоков T (OP_CheckSequenceVerify). Например, через 48 блоков, то есть примерно 8 часов.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*konN3MnGrqxXg1jfkPuZtA.png" /><figcaption>Финальный вид транзакций, используемых для платежного канала.</figcaption></figure><p>Если Алиса подписывает одну из своих транзакций (они уже подписаны Бобом), и транслирует эту транзакцию в блокчейн, то возможны два сценария.</p><ol><li>Алиса транслирует финальную транзакцию =&gt; Боб не знает последнего ключа Алисы <em>AKi</em>. Это корректное закрытие канала, все должны получить свои деньги. Алиса получит их через какое-то время.</li><li>Алиса пытается записать старую транзакцию вместо финальной =&gt; Алиса пытается обмануть Боба. В этом случае Боб знает ключ Алисы и он может воспользоваться им, чтобы получить все средства Алисы. Разумеется, Алиса не заинтересована в этом сценарии.</li></ol><p>Итак, <em>“проблема последней транзакции”</em> тоже решена и платежный канал между двумя людьми готов. Теперь также становятся очевидны некоторые плюсы и минусы.</p><blockquote><strong><em>👍</em> Преимущества:</strong> 1. платежи внутри канала мгновенны и бесплатны, они не создают нагрузки на главный блокчейн. 2. стороны не обязаны доверять друг другу.</blockquote><blockquote><strong><em>👎</em> Недостатки:</strong> 1. депозиты заблокированы на все время существования канала. 2. обе стороны должны периодически появляться онлайн (как минимум раз в <em>T</em>).</blockquote><p><strong>👌</strong> На самом деле оба недостатка важны для платежных каналов между двумя людьми, но не очень важны в контексте Lightning Network. Первый недостаток перестает быть недостатком, если один платежный канал может быть использован для транзакций с разными людьми.</p><p>Второй недостаток отсутствует в LN, так как проверку корректности может совершать любой участник сети (если Вася вскроет мошенничество Алисы, то он разделит с Бобом конфискованные средства Алисы).</p><h3>4. Lightning Network</h3><h4>4.1. Платежный канал через посредника</h4><p>Предположим теперь, что Алиса и Боб не имеют открытого канала между собой, но они оба поддерживают открытый канал с Витей. Алиса может безопасно передать деньги Вите, Витя может безопасно передать деньги Бобу.</p><p>Но как убедиться, что Витя, получив деньги, действительно передаст их дальше Бобу?</p><p>На самом деле идея немного похожа на предыдущий трюк, только вместо одноразовых ключей используется некоторое секретное число.</p><ol><li>Боб генерирует секретное число <em>S</em>, хэш от этого секретного ключа <em>HS</em> и передает эту информацию Алисе. <em>HS</em> при этом может использоваться как виртуальный чек.</li><li>Алиса создает транзакцию <em>AV</em>, которая передает деньги Вите, но только в случае, если Витя предоставит секретное число <em>S</em>. Для этого она использует скрипт, который проверяет равенство хэша предоставленного числа и значения <em>HS</em> (тут как раз и используются операции OP_SHA256 и OP_EqualVerify).</li><li>Витя создает аналогичную транзакцию <em>VB</em>, которая передает деньги Бобу, но только в случае, если Боб предоставит секретное число.</li><li>Боб видит, что он может получить деньги от Вити, и показывает ему секретное число <em>S</em>.</li><li>Витя теперь может доказать, что он передал деньги Бобу, и соответственно он может обналичить транзакцию <em>AV</em>.</li></ol><p>Тут есть несколько вариантов развития событий.</p><ol><li>Во-первых, Вите не имеет смысла обманывать Алису. Он не может не передать деньги Бобу, потому что иначе Витя все равно не получит деньги от Алисы.</li><li>Но Боб может решит обмануть Витю и не передать ему секретное число. При этом он может закрыть канал с Витей и записать транзакцию <em>VB</em> в блокчейн. Но для вывода денег ему все равно придется показать свое секретное число, и тут-то Витя его и узнает.</li></ol><p>Тут есть пара нетривиальных нюансов с тем, как выбрать время, в течении которого Алиса, Боб и Витя могут разрешить конфликты. Но эти более технические подробности выходят за рамки этой вводной статьи. Если интересно — гуглите <em>Hash Time-Locked Contracts (HTLCs)</em>.</p><h4>4.2. Маршрутизация</h4><p>На практике Алиса и Боб могут быть связаны между собой не через одного общего знакомого Витю, а через несколько неизвестных/анонимных посредников по всему миру. Проблема поиска пути в графе узлов сети называется <em>проблемой маршрутизацией</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*933GpxVj8PzBVPMQGbDeng.png" /><figcaption>Географическое распределение узлов тестовой сети (<a href="https://explorer.acinq.co/#/">https://explorer.acinq.co/#/</a>).</figcaption></figure><p>Вопрос маршрутизации на самом деле является областью активных исследований на данный момент. Оптимальный путь в графе зависит от многих динамических факторов: наличия узлов, топологии сети, пропускной способности каналов, комиссии промежуточных узлов.</p><p>Не вдаваясь в подробности, поиск пути и передача платежей в LN реализуется на основе <a href="https://en.wikipedia.org/wiki/Onion_routing"><em>Onion routing</em></a><em> — </em>технологии анонимного распространения информации по <em>peer-to-peer</em> сетям. Именно так, например, работает <a href="https://www.torproject.org/">Tor</a>.</p><p>Все децентрализовано, весь трафик зашифрован. Никто не знает, от кого пришли деньги и кому они пойдут дальше. Отсюда еще одно преимущество.</p><blockquote><strong><em>👍</em> Преимущества:</strong> Lightning Network намного более анонимна, чем сам биткоин. Во-первых, промежуточные транзакции не записываются в публичный блокчейн, их видит всего несколько участников. Во-вторых, даже среди этих участников, только первый и последний человек точно знают, от кого и кому переводятся средства.</blockquote><h4>4.3. Экономика комиссий</h4><p>Остается два очевидных вопроса.</p><p><strong>Вопрос номер 1:</strong> зачем посредникам обрабатывать чужие платежи?</p><p>Во-первых, потому что им самим так проще пользоваться LN. Во-вторых, потому что они получают с этого <em>очень маленькую</em>, но все-таки комиссию.</p><p>На данный момент сеть поддерживают в основном энтузиасты и комиссия практически нулевая: 1 сатоши, или ~0.01 <em>цента</em> за каждого посредника.</p><blockquote><strong><em>👍</em> </strong>Пропускная способность каналов — намного менее ценный ресурс, чем размер блока. Каналы открывать просто и недорого. Поэтому комиссии в LN на порядки ниже комиссий в основном блокчейне.</blockquote><p><strong>Вопрос номер 2:</strong> а как же комиссия за открытие/закрытие канала?</p><p>Действительно, эта комиссия может иногда составлять десятки долларов. Таким образом, платежи будут тем выгоднее, чем реже придется открывать/закрывать каналы.</p><p>Это мотивирует людей открывать каналы с б<strong><em>о</em></strong>льшими депозитами, и использовать каналы в двух направлениях: не только для исходящих платежей, но и для получения средств.</p><p><em>Пример:</em> я открываю канал, зачисляю туда 1000 долларов, и использую канал только для исходящих платежей. Оборот в канале составит 1000 долларов, примерно 20 долларов уйдет на открытие и закрытие канала. То есть суммарно комиссии составят 2%. Немного лучше, чем виза и мастеркард, но явно больше, чем хотелось бы.</p><p>Ситуация кардинально меняется, когда я начинаю использовать Lightning на всю катушку: вкладывать б<strong><em>о</em></strong>льшие суммы и получать деньги через каналы, а не только тратить их. Тогда, в зависимости от пропорции полученных/потраченных денег, <em>канал может быть открыт вечно и комиссии в пределе будут стремиться к нулю</em>.</p><h4>4.4. Критика</h4><p>В интернете можно найти большое количество критики решений второго уровня в целом и Lightning Network в частности. Какие-то пункты действительно заслуживают внимания, многие оказываются устаревшими. Приведем несколько примеров.</p><blockquote>1. Использование LN приведет к централизации: пользователям будет выгодно подключаться к крупным хабам и эти хабы будут контролировать весь трафик.</blockquote><p>Такой риск есть и стоит уделять этому внимание, но риск не очень велик. Во-первых, экономически выгодно и очень просто будет создать новый узел в обход больших хабов. Во-вторых, алгоритмы маршрутизации предусматривают балансировку трафика. В-третьих, пока что такой картины <a href="https://lnmainnet.gaben.win/">не наблюдается</a>. В будущем, я надеюсь, топология сети будет оптимально выстраиваться алгоритмически.</p><blockquote>2. Недостаточная пропускная способность каналов приведет к тому, что LN будет забита, комиссии будут расти, и вскоре ситуация будет такой же, как и в основном блокчейне.</blockquote><p>Опять же, как только такое начнет происходить, у людей появится большая экономическая мотивация запускать свои узлы. В отличии от размера блока, количество узлов практически неограниченно.</p><blockquote>3. Эффективная маршрутизация на большом количестве peer-to-peer узлов невозможна. Особенно с учетом сложности открытия новых каналов.</blockquote><p>До этих проблем еще <em>очень и очень и очень далеко</em>, а исследования в этом направлении активно ведутся уже сейчас. Что-нибудь придумают.</p><blockquote>4. Каналы нужно постоянно открывать и закрывать, комиссии, потраченные на это, будут огромны и LN окажется невыгодной.</blockquote><p>На самом деле это проблема из прошлого, про которую почему-то до сих пор говорят. Ранние версии платежных каналов действительно были однонаправленными, а сам канал мог существовать только ограниченное время. Сейчас эти проблемы решены.</p><blockquote>5. Для использования LN необходимо быть онлайн.</blockquote><p>Опять же, в отличии от ранних реализаций LN, пользователю нет необходимости все время быть онлайн: другие узлы сети проверяют, что два владельца канала не пытаются обмануть друг друга. Действительно необходимо быть онлайн только для отправки и получения платежей, что безусловно является ограничением, но уже намного менее важным.</p><blockquote>6. LN не совместимо с холодными хранилищами (cold storage).</blockquote><p>Очень правильно замечание. Депозиты платежных каналов храняться в кошельке подключенном к интернету (<em>hot wallet</em>). Для защиты от хакеров необходимо будет очень серьезно подходить к безопасности.</p><blockquote>7. LN платежи — это не безопасно.</blockquote><p>LN платежи действительно чуть более опасны, чем платежи на основном блокчейне. Но только в одном случае: <a href="https://blog.bitmex.com/the-lightning-network/">при успешной 51% атаке на блокчейн биткоина</a>. Риск этого ничтожно мал.</p><h3>5. LN сегодня</h3><p>Самое важное, что вам нужно знать: Lightning уже реально работает.</p><p><a href="https://explorer.acinq.co/#/">Более тысячи узлов</a> в тестовой сети биткоина и <a href="https://lnmainnet.gaben.win/">более двухсот узлов</a> (число растет каждый день) в основной сети (<em>mainnet</em>) уже обрабатывают платежи и тестируют различный софт.</p><h3>elizabeth stark on Twitter</h3><p>@TraceMayer @Blockstream @coinbase @BitPay @adam3us Bug testing should be on testnet, not mainnet. Especially when the devs are still losing money. 🙃 https://t.co/QYx94V0vpR</p><p>Что касается софта, то есть три основных реализации: <a href="https://github.com/lightningnetwork/lnd">lnd</a> от <em>Lightning Labs</em>, <a href="https://github.com/ElementsProject/lightning">c-lightning</a> от <em>Blockstream</em>, <a href="https://github.com/ACINQ/eclair">eclair</a> от <em>ACINQ</em>. Эти команды уже не один год работали совместно, чтобы разработать общий стандарт взаимодействия узлов: <a href="https://github.com/lightningnetwork/lightning-rfc"><em>Lightning Network Specifications (BOLTs)</em></a>. И вот буквально в конце 2017-ого года они провели полномасштабное успешное тестирование протокола платежей, все три реализации оказались совместимы.</p><p>Расплатиться реальными биткоинами используя LN можно пока буквально в трех-четырех онлайн-магазинах. Но это на целых три-четыре магазина больше, чем всего месяц назад, так что это уже большой успех 😊</p><p>Конечно, момент повсеместного перехода с <em>on-chain</em> биткоин платежей на <em>off-chain</em> платежи еще далеко. Огромную работу еще должны провести разработчики кошельков, платежных шлюзов, бирж, онлайн-магазинов. И, конечно, сами пользователи.</p><p>Самое интересное в этой истории, что более быстрые, анонимные и дешевые платежи — это только начало! На подходе еще больше анонимности, атомарные свопы, распределенные биржи и многое-многое другое. Будущее выглядит захватывающе! ⚡</p><p><em>Больше подробностей про LN по ссылкам: </em><a href="https://lightning.network/lightning-network-paper.pdf"><em>1</em></a><em>, </em><a href="https://github.com/bitcoin/bips/blob/master/bip-0112.mediawiki"><em>2</em></a><em>, </em><a href="https://github.com/lightningnetwork/lightning-rfc"><em>3</em></a><em>, </em><a href="https://github.com/ElementsProject/lightning/blob/master/doc/deployable-lightning.pdf"><em>4</em></a><em>, </em><a href="https://blog.bitmex.com/the-lightning-network/"><em>5</em></a><em>.</em></p><p>Комментируйте, критикуйте, задавайте вопросы, подписывайтесь! Авторский мини-канал про крипту в телеграме: <a href="https://t.me/cryptohodl">https://t.me/cryptohodl</a>. Больше об авторе: <a href="http://laptev.ch/">http://laptev.ch</a>. По вопросам использования материала пишите на d@laptev.ch или <a href="https://t.me/x0100">https://t.me/x0100</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c618c9cd68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Биткоин: транзакции, пластичность, SegWit и масштабируемость]]></title>
            <link>https://x0100.medium.com/%D0%B1%D0%B8%D1%82%D0%BA%D0%BE%D0%B8%D0%BD-%D1%82%D1%80%D0%B0%D0%BD%D0%B7%D0%B0%D0%BA%D1%86%D0%B8%D0%B8-%D0%BF%D0%BB%D0%B0%D1%81%D1%82%D0%B8%D1%87%D0%BD%D0%BE%D1%81%D1%82%D1%8C-segwit-%D0%B8-%D0%BC%D0%B0%D1%81%D1%88%D1%82%D0%B0%D0%B1%D0%B8%D1%80%D1%83%D0%B5%D0%BC%D0%BE%D1%81%D1%82%D1%8C-c581ece107ba?source=rss-31fdaacddcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/c581ece107ba</guid>
            <category><![CDATA[блокчейн]]></category>
            <category><![CDATA[segwit]]></category>
            <category><![CDATA[пластичность-транзакций]]></category>
            <category><![CDATA[масштабируемость]]></category>
            <category><![CDATA[биткоин]]></category>
            <dc:creator><![CDATA[Dmitry Laptev]]></dc:creator>
            <pubDate>Thu, 24 Aug 2017 06:00:55 GMT</pubDate>
            <atom:updated>2017-12-26T15:28:41.472Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/@x0100/258af8ed9cbf"><em>This article in English.</em></a></p><p>Итак, сообщество биткоина добилось своего: майнеры согласились на SegWit и он таки активировался сегодня в сети. Паника немного улеглась, цена подросла… Пришла пора разобраться, что же такое этот SegWit, почему все о нем говорят, и зачем он нужен.</p><blockquote>Дисклеймер. Я сознательно опускаю/упрощаю некоторые технические моменты. А еще я не эксперт, и могу банально ошибаться.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B1SBUa2DCeJ0gVEf6NQ0Eg.png" /></figure><p><strong>Segregated Witness (SegWit)</strong> — это собирательное название для нескольких изменений в протоколе биткоин. Многие из этих изменений заслуживают отдельного внимания, но я буду фокусироваться на первом и главном: изменение того, как считается <em>идентификатор транзакции</em>.</p><p>Хотя в последнее время все говорят о SegWit только в контексте споров о масштабировании, изначальное предложение решало совсем другую проблему: <em>transaction malleability</em>, или, как принято это переводить на русский, <em>пластичность транзакций</em>.</p><p>Но обо всем по порядку: что такое транзакция?</p><h3>Транзакция</h3><p>Для простоты будем рассматривать транзакцию с адреса <em>A</em> на адрес <em>B</em>, с одним входом и одним выходом. <a href="https://blockchain.info/tx/5a4ebf66822b0b2d56bd9dc64ece0bc38ee7844a23ff1d7320a88c5fdb2ad3e2">Пример такой транзакции</a>:</p><pre>Input:<br>Previous tx: f5d8ee39a430901c91a5917b9f2dc19d6d1a0e9cea205b009ca73dd04470b9a6<br>Index: 0<br>scriptSig: 304502206e21798a42fae0e854281abd38bacd1aeed3ee3738d9e1446618c4571d1090db022100e2ac980643b0b82c0e88ffdfec6b64e3e6ba35e7ba5fdd7d5d6cc8d25c6b241501</pre><pre>Output:<br>Value: 5000000000<br>scriptPubKey: OP_DUP OP_HASH160 404371705fa9bd789a2fcd52d2c580b65d35549d OP_EQUALVERIFY OP_CHECKSIG</pre><ul><li>Previous tx — идентификатор предыдущей транзакции на адрес <em>A</em>;</li><li>Index — номер входа (в этом примере один вход с номером 0);</li><li>scriptSig — первая часть проверяющего скрипта (об этом ниже);</li><li>Value — количество биткоинов, указанное в сатоши (один биткоин = 100 миллионов сатоши) — 50 биткоинов в примере;</li><li>scriptPubKey — вторая часть проверяющего скрипта, которая также содержит адрес получателя <em>B</em>.</li></ul><p>Транзакции всегда выстраиваются в цепочку (на самом деле в дерево, но это детали). Чтобы потратить биткоины <em>с адреса</em> <em>A</em>, нужно потратить выход каких-то транзакций <em>на адрес</em> <em>A </em>(за исключением coinbase транзакций, у которых ноль входов, но это тоже детали).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*Dz42akQohXCwUKtZzdG9hw.png" /></figure><p>Чтобы проверить, что мы можем тратить выход предыдущей транзакции, мы должны:</p><ol><li>Соединить scriptSig новой транзакции со scriptPubKey предыдущей транзакции,</li><li>Проверить, что получившийся скрипт (на специальном языке программирования <em>Script</em>) выполняется и возвращает True.</li></ol><p>В самом простом случае (как в примере выше) scriptSig содержит подпись транзакции приватным ключем, а scriptPubKey просто проверяет совпадение публичного ключа и валидность подписи для данного адреса (основная операция: OP_CHECKSIG).</p><p>Не нужно изобретать отдельный язык программирования, чтобы проверять такие простые случаи. Но возможности биткоина намного больше. Например, с помощью такого механизма можно реализовать MultiSignature адреса, средства с которых можно потратить только при условии подписи несколькими ключами. <a href="http://telegra.ph/Vvedenie-v-smart-kontrakty-07-04">Немного больше про это</a>.</p><h3>Пластичность транзакций</h3><p>Что же конкретно содержится в поле Previous tx, спросите вы? Что это за <em>идентификатор транзакции (transaction identifier, txid)</em>?</p><blockquote>txid — это sha256d хэш от всех полей данных транзакции.</blockquote><p>Ключевым моментом является зависимость от scriptSig. Потому что scriptSig сама по себе как правило содержит данные о транзакции подписанные приватным ключем, включая <em>txid</em>. scriptSig зависит от <em>txid</em>, поэтому <em>txid</em> не может зависеть от scriptSig.</p><p>Любой держатель полной ноды биткоин (не только майнер) помогает собирать и распространять по сети данные о транзакциях. В процессе он может изменить scriptSig таким образом, чтобы скрипт подписи оставался корректным, результат транзакции оставался тем же, <em>но txid поменялся</em>.</p><p>Например, к любой подписи можно добавить операцию OP_NOP (не делает ничего), или для изощренности добавить две операции OP_DUP OP_DROP (первая дублирует подпись на стеке, а вторая удаляет верхний элемент стека). Подпись останется корректной, но <em>txid</em> поменяется.</p><p>И вот тут-то кроется проблема. Точнее две.</p><h4>1. txid — плохой идентификатор</h4><p>Такая изменяемость идентификатора не позволяет использовать <em>txid</em> по назначению: как идентификатор. Злоумышленник может перехватить нормальную транзакцию и распространить модифицированную версию по сети. С некоторой вероятностью майнеры могут включить в блок модифицированную транзакцию вместо изначальной.</p><p>Зачем это нужно злоумышленнику, спросите вы? В идеальном мире — особо незачем. Но в реальном мире люди любят использовать идентификаторы для уникальной идентификации. Это и произошло (<a href="https://qz.com/175565/why-nobody-can-withdraw-bitcoins-from-one-of-the-currencys-largest-exchanges/">по одной из версий</a>) с биржей MtGox.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yun4v8Y-Dhu-TL0Ed2OEJA.png" /></figure><p>Злоумышленник выводил биткоины с этой печально известной биржи, перехватывал транзакцию, менял ей <em>txid</em>. Транзакция оставалась валидной, злоумышленник получал свои биткоины. Но биржа видела, что изначальный <em>txid</em> не вошел в блок и не уменьшала баланс злоумышленника.</p><h4>2. Цепочки транзакций в одном блоке</h4><p>Есть еще и вторая проблема. А точнее упущенная возможность.</p><p>Теоретически биткоин позволяет тратить выход транзакций, которые еще не были включены в блок. Я могу перевести средства с адреса <em>A</em> на адрес <em>B</em>. А потом, не дожидаясь подтверждения первой транзакции, перевести биткоины с адреса <em>B</em> на адрес <em>C</em>. И обе эти транзакции могли бы быть проверены и одновременно включены в блок, если бы не пластичность.</p><p>Если <em>txid</em> первой транзакции может измениться, значит Previous tx второй транзакции может измениться, а значит и подпись может измениться. А значит вторую транзакцию проверить нельзя, пока первая не будет включена в блок (тогда ее <em>txid</em> будет зафиксирован).</p><p>И это проблема больше, чем кажется на первый взгляд, но об этом в самом конце.</p><h3>Segregated Witness</h3><p>На самом деле теперь все становится очень просто.</p><blockquote>SegWit предлагает: давайте вынесем всю пластичную информацию из транзакции отдельно (witness data), а txid будем считать без нее. Идентификатор станет уникальным, проблемы будут решены.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSsXLElVEZ2adtZsEtTJCQ.png" /><figcaption>Транзакция до и после. scriptSig теперь всегда пуст, данные перемещаются в отдельную структуру “Witness data”. Все остальное остается также: <em>txid и размер транзакции вычисляются из тех же полей, что и раньше</em>.</figcaption></figure><p>Элементарное решение, не правда ли? Но оно меняет определение транзакции (которое почти не менялось с самого начала), меняет механизмы валидации, требует переписать огромное количество очень стабильного кода. А еще неплохо было бы подумать про сохранение совместимости.</p><p>Поэтому (а также из-за политических игр, про которые я не буду здесь рассказывать) принятие SegWit заняло так долго.</p><h3>При чем здесь масштабирование?</h3><p>Оказывается, этот фикс имеет огромное влияние на масштабирование биткоина. По двум причинам.</p><h4>1. Больше транзакций в блоке</h4><p>Посмотрите еще раз на пример транзакции выше по тексту. Больше половины информации в ней — это scriptSig. Вынося эту информацию отдельно, мы по сути снижаем размер транзакции. И эффективно увеличиваем размер блока.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-DML0FPOd4Nzj_l4Au8PQ.jpeg" /></figure><p>Конечно, это читерство, потому что подпись мы тоже будем хранить, хоть и отдельно. Но при вычислении размера блока эти данные не учитываются. Почему не учитываются? Не вдаваясь в детали, потому что только так можно было реализовать SegWit через <em>soft fork</em>. <a href="http://telegra.ph/Pro-forki-v-kriptovalyutah-06-10">Чуть больше про форки</a>.</p><p>Теоретически, в блок можно будет впихнуть в четыре раза больше транзакций. Практически — примерно в два раза больше. Вполне себе ощутимое масштабирование.</p><h4>2. Транзакции вне блокчейна и lightning network</h4><p>На данный момент абсолютно все транзакции хранятся в блокчейне. Тысячи компьютеров по всему миру хранят информацию о том, что я купил кофе за 0.0015 биткоина. Это дорого для узлов сети. Это дорого и долго для меня: каждый раз мне нужно ждать 10 минут подтверждения транзакции за кофе.</p><blockquote>Один из вариантов решения этой проблемы — проводить небольшие транзакции вне основного блокчейна. И время от времени синхронизировать баланс на главном блокчейне. Общее название этого подхода — second layer networks (сети второго уровня).</blockquote><p>Одним из рабочих решений в этом стиле на данный момент считается <a href="https://lightning.network/lightning-network-paper.pdf"><em>Lightning network</em></a>. Работает это примерно так:</p><ul><li>два человека открывают между собой <em>канал микроплатежей, </em>у обоих блокируется по некоторой сумме;</li><li>они совершают много небольших транзакций между собой;</li><li>честное поведение гарантируется за счет умной криптографии, конфликты разрешаются из заблокированных средств;</li><li>как только канал закрывается — на главном блокчейне появляется одна транзакция, которая синхронизирует балансы людей, замороженные суммы возвращаются.</li></ul><p>Настоящая сила каналов проявляется, когда их много. Каналы формируют ребра в графе людей. Если между двумя людьми есть путь, даже через несколько каналов — они могут совершать транзакции.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*lx7px12VhzrX-W3u5p5CTA.jpeg" /></figure><p>Причем тут SegWit, спросите вы? Он действительно не обязателен, но делает имплементацию намного удобнее.</p><p>Не углубляясь в детали… Для работы канала микроплатежей необходимо создать транзакцию подписанную двумя сторонами (<em>double-signed transaction</em>). В самом начале на адрес с двумя ключами отправляются средства. Но чтобы предотвратить мошенничество, double-signed transaction<em> </em>должна быть подписана <em>до того</em>, как туда переведут деньги.</p><p>Но чтобы провернуться такое, необходимо собрать выходы транзакций, которые еще не были подтверждены на главном блокчейне. А это как раз тот сценарий, который на данный момент невозможен из-за пластичности транзакций (смотрите пункт “2. Цепочки транзакций в одном блоке” выше по тексту). И тут-то SegWit приходит на помощь.</p><h4>Заключение</h4><p><strong>TL;DR.</strong> SegWit активирован. На самом деле он решает проблему пластичности транзакций, но еще оказывается полезен для масштабирования. Краткосрочно он позволит включать больше транзакций в блоки. Долгосрочно — открывает новые возможности масштабирования через <em>off-chain</em> транзакции. С нетерпением ждем, что из этого получится.</p><p>Комментируйте, критикуйте, задавайте вопросы, подписывайтесь! Больше интересных статей в телеграме: <a href="https://t.me/cryptohodl">https://t.me/cryptohodl</a>. Больше обо мне: <a href="http://laptev.ch/">http://laptev.ch</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c581ece107ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bitcoin: transactions, malleability, SegWit and scaling]]></title>
            <link>https://medium.com/lightningto-me/bitcoin-transactions-malleability-segwit-and-scaling-258af8ed9cbf?source=rss-31fdaacddcaa------2</link>
            <guid isPermaLink="false">https://medium.com/p/258af8ed9cbf</guid>
            <category><![CDATA[segwit]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[transaction-malleability]]></category>
            <dc:creator><![CDATA[Dmitry Laptev]]></dc:creator>
            <pubDate>Thu, 24 Aug 2017 05:59:00 GMT</pubDate>
            <atom:updated>2017-08-25T15:45:46.395Z</atom:updated>
            <content:encoded><![CDATA[<p>As of today, bitcoin community has finally achieved its long awaited goal: SegWit was activated. The panic is over (at least for the moment), the price has climbed up… It’s time to figure out: what is this SegWit, why everyone is talking about, and why do we need it in the first place?</p><blockquote>Disclaimer. I consciously omit/simplify some of the technical details. And also I am not an expert, and can be simply wrong.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B1SBUa2DCeJ0gVEf6NQ0Eg.png" /></figure><p><strong>Segregated Witness (SegWit)</strong> is a cumulative name for a bunch of changes to bitcoin protocol. Many of these changes deserve exclusive attention, but I will be focusing on only the first (and the most important) one: a change to how <em>transaction identifier</em> is computed.</p><p>Despite the fact that recently all the talks about SegWit are related to a scaling debate, the initial proposal was solving a very different problem: <em>transaction malleability</em>.</p><p>But let’s move one step at a time: what is a bitcoin transaction?</p><h3>Transaction</h3><p>For simplicity, let’s consider a transaction from an address <em>A</em> to an address <em>B</em> with a single input and a single output. <a href="https://blockchain.info/tx/5a4ebf66822b0b2d56bd9dc64ece0bc38ee7844a23ff1d7320a88c5fdb2ad3e2">An example of such a transaction</a>:</p><pre>Input:<br>Previous tx: f5d8ee39a430901c91a5917b9f2dc19d6d1a0e9cea205b009ca73dd04470b9a6<br>Index: 0<br>scriptSig: 304502206e21798a42fae0e854281abd38bacd1aeed3ee3738d9e1446618c4571d1090db022100e2ac980643b0b82c0e88ffdfec6b64e3e6ba35e7ba5fdd7d5d6cc8d25c6b241501</pre><pre>Output:<br>Value: 5000000000<br>scriptPubKey: OP_DUP OP_HASH160 404371705fa9bd789a2fcd52d2c580b65d35549d OP_EQUALVERIFY OP_CHECKSIG</pre><p>And here is what it means:</p><ul><li>Previous tx — an identifier of the previous transaction to the address <em>A;</em></li><li>Index — input number (here we have only one input number 0);</li><li>scriptSig — first part of the validation script (more about it below);</li><li>Value — the number of bitcoins to send in satoshi (one bitcoin = 100 millions satoshi) — 50 bitcoins in the example;</li><li>scriptPubKey — second part of the validation script, which also contains the receiver address <em>B</em>.</li></ul><p>Transactions are linked in chains (well, in trees in fact, but this does not matter for now). To spend bitcoins <em>from address A</em>, one needs to spend the output of some transactions <em>to address A</em> (except of <em>coinbase</em> transactions rewarding miners for generating a block, these transactions have zeros inputs).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*Dz42akQohXCwUKtZzdG9hw.png" /></figure><p>To verify that one can spend the output of the previous transaction, one needs to:</p><ol><li>Combine scriptSig of a new transaction with the scriptPubKey of the previous transaction,</li><li>Check that the resulting script (written in a special language called, you guessed it, <em>Script</em>) is valid and returns True.</li></ol><p>In the simplest case (like in this example), scriptSig contains a transaction signature (signed with a private key from this address), and scriptPubKey simply checks the equality of the public key and the validity of the signature (the main operation here is OP_CHECKSIG).</p><p>Of course, one does not need a special programming language just to handle these simple cases. But <em>Script</em> enables bitcoin to do much more. For example, using this mechanism, one can create a <em>MultiSignature</em> address — an address, from which one can spend funds only in case the transaction is signed by multiple keys from different parties.</p><h3>Transaction malleability</h3><p>To explain what transaction malleability is, we need to clarify one point: what exactly is <em>transaction identifier</em> or simply <em>txid</em>?</p><blockquote>txid is a sha256d hash of all the fields of the transaction data.</blockquote><p>What is relevant in this definition, is that <em>txid</em> depends on scriptSig.</p><p>Every full node in the bitcoin network (not only miners) helps to collect and distribute information about transactions. In the process, the node can mutate scriptSig in such a way, that the signature will stay valid, the transaction will have the same effect, <em>but txid will change</em>.</p><p>For example, one can add a OP_NOP operation (that does nothing). Or for some sophistication, one can add two operations: OP_DUP OP_DROP (the first one is duplicating the signature on the stack, and the second one removes it again). The signature is still valid, but <em>txid</em> changes.</p><p>And now we can see a problem. Two problems, in fact.</p><h4>1. txid is a bad identifier</h4><p>This mutability do not permit the usage of <em>txid</em> as it was intended: as an identifier. An attacker can intercept a normal transaction and distribute the modified version through the network. With some probability the miners will include this modified transaction instead of the original one.</p><p>You may ask: <em>why would an attacker do that</em>? In ideal world there is indeed not much of a point to do that. But in real world people like using identifiers for unique identification. And this is what happened to <a href="https://qz.com/175565/why-nobody-can-withdraw-bitcoins-from-one-of-the-currencys-largest-exchanges/">MtGox exchange in 2013</a> (this is only one of the versions, they could have simply stolen the funds themselves).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yun4v8Y-Dhu-TL0Ed2OEJA.png" /></figure><p>An attacker was withdrawing the funds from the exchange, intercepting the transaction, and changing its <em>txid</em>. The transaction was still valid and the attacker got the bitcoins. But the exchange saw that <em>txid</em> was never included in the block and did not decrease the attackers balance.</p><h4>2. Transaction chains in one block</h4><p>The second problem is rather not a problem, but a missed opportunity.</p><p>Theoretically bitcoin allows to spend the outputs of transactions even before they were included in the block. One can transfer funds from <em>A</em> to <em>B</em>. And then, without waiting for any confirmations, transfer bitcoins from <em>B</em> to <em>C</em>. And both transactions could have been validated and included in the next block, if not for transaction malleability.</p><p>If <em>txid</em> of the first transaction can change, the Previous tx field of the second transaction should also change. And it means that the second transaction can only be created when the first transaction is included in a block (and therefore its <em>txid</em> is fixed).</p><p>And this problem is bigger than one might think, but we will come to it later.</p><h3>Segregated Witness</h3><p>And now it becomes easy to explain what SegWit proposal is all about.</p><blockquote>SegWit suggests: let’s separate all the malleable information from the transaction into a separate “witness data”. txid will be computed without it, the identifier will never be able to change, the problems will be fixed.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSsXLElVEZ2adtZsEtTJCQ.png" /><figcaption>Transaction schema before and after SegWit. scriptSig is now empty, the data moves to a separate “witness data”. Everything else stays the same: <em>txid and transaction size </em>are still computed from the same fields as before.</figcaption></figure><p>Easy, right? Yes, but it changes the transaction definition (that was not changed much since the beginning), changes the validation mechanisms, requires huge code changes. And on top of it, would be nice to make SegWit compatible with the previous protocol versions.</p><p>Because of all that (and also because of some political games, which I am not going to talk about), SegWit activation took so long.</p><h3>What does it have to do with scaling?</h3><p>Apparently, this fix also have a huge impact on the scaling of bitcoin. Because of two reasons.</p><h4>1. More transactions in a block</h4><p>Look once again at the transaction example above. More than half of the data is scriptSig. Separating this data, we essentially allow transactions to be smaller. And effectively enlarge the block size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-DML0FPOd4Nzj_l4Au8PQ.jpeg" /><figcaption>Huge lego blocks in front of The Lego Group headquarters</figcaption></figure><p>Of course this is cheating, because we still need to store all these signatures. But now this data does not count towards the block size limit. Why not? Without going into details: because this was the only way to implement SegWit as a <em>soft fork</em>, and not a <em>hard fork</em>. And nobody likes hard forks.</p><p>Theoretically, new SegWit blocks can include up to four times more transactions. Practically — about two times more. Quite a tangible scaling.</p><h4>2. Off-chain transaction and lightning network</h4><p>Currently, every bitcoin transaction ever made is stored in bitcoin blockchain. Thousands of computers around the world are storing information about me buying coffee for 0.001 bitcoins.</p><p>This is expensive for the nodes of the network. This is expensive and annoying for me: I have to pay large fees and wait for ten minutes for the confirmation of my transaction.</p><blockquote>One of many possible solutions to this problem is to have some small transactions executed off the main chain, and then sometimes sync the balance. The common name for these approaches is “second layer network”.</blockquote><p>One close-to-working implementation of this idea is <a href="https://lightning.network/lightning-network-paper.pdf"><em>Lightning network</em></a>. It works approximately like this:</p><ul><li>two persons open a <em>micropayment channel</em> between each other, both have some amount of funds locked;</li><li>they execute large number of small transactions between each other;</li><li>honest behaviour is guaranteed by some very clever crypto-magic, conflicts are automatically resolved from the locked funds;</li><li>as soon as the channel is closed — the locked funds are unlocked, the balances are synced to the main blockchain.</li></ul><p>The real power of the payment channels is achieved when there are many of them. Channels form edges of the graph between people. If two people are connected, even indirectly — they can transact between each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*lx7px12VhzrX-W3u5p5CTA.jpeg" /></figure><p>What does SegWit has to do with that? It is indeed not necessary, but it makes the implementation much easier.</p><p>Without going into too many details… Micropayment channels rely on <em>double-signed transactions</em> to lock the initial deposits. In the beginning, the funds from both parties are sent to one double-signed address. To prevent cheating, the transaction should be double-signed <em>before</em> any funds are actually sent there.</p><p>But to do that, one needs to collect the outputs of transactions that were not yet synced to the main blockchain. And this is exactly the scenario not permitted because of transaction malleability (described above in “2. Transaction chains in one block”). And this is where SegWit comes to the rescue.</p><h4>Conclusion</h4><p><strong>TL;DR.</strong> SegWit is activated. It solves the problem of transaction malleability, but it is also useful for scaling. Short-term is will permit more transactions in a single block. Long-term it will open new opportunities for off-chain transactions. Looking forward to the future!</p><p>Please do comment, criticize, ask questions, subscribe. More about myself: <a href="http://laptev.ch/">http://laptev.ch</a>.</p><p><a href="https://medium.com/@x0100/c581ece107ba">This article in Russian (статья на русском).</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=258af8ed9cbf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lightningto-me/bitcoin-transactions-malleability-segwit-and-scaling-258af8ed9cbf">Bitcoin: transactions, malleability, SegWit and scaling</a> was originally published in <a href="https://medium.com/lightningto-me">LightningTo.Me</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>