 All right welcome everyone, this is a technical presentation on the lightning network. These slides are available under a Creative Commons attribution share like license as you can see in the bottom right hand corner and you can download them at any time including right now and look at them on your own system. And of course you can also use them for mashups and reuse them in any way you want under the Creative Commons license. Thank you so much for joining me today. This presentation will be a bit technical and it does require a basic understanding of the bitcoin system but I will cover some of the introductory information and all of the necessary background. If you want to learn more about the things I'm going to talk about today there are two books that are available again under Creative Commons license, Mastering Bitcoin Second Edition which you can find on GitHub in the Bitcoin Book Repository and Organization and you can read the book most of the material today is from chapter 12 but sections of the material are also from chapters four and five. As we're looking at this book today I'm also working on my next book Mastering the Lightning Network again from O'Reilly Media which is also being developed under an open source license and you can find that online. The first couple of chapters have been drafted and you can watch the progress as we make it chapter by chapter paragraph by paragraph line by line typo by typo and spelling mistake by spelling mistake you can watch this book progress. If you want additional information about the Lightning Network and like to watch videos instead of reading a book perhaps you might want to check out the YouTube channel and I have a link here where you can find 40 videos that are ad-free specifically on the topic of the Lightning Network from my Q&A series you can also find 500 other videos that are not about Lightning necessarily. So let's get started what is the Lightning Network? The Lightning Network is according to the definition a specific design for a routed payment channel network which has been implemented by at least five different open source teams and these independent implementations are coordinated by a set of interparability standards a specification if you like as defined in the basis of lightning technology or bolt standards and you can find those and read them online they're like rfcs in that they define exactly how the protocol works in this presentation today we're going to cover some of the basic prerequisites that are necessary in order to start understanding what the Lightning Network is and how it works and I'm going to cover some of the basics of bitcoin very very briefly just to give you a foundation we'll talk about bitcoin transactions bitcoin script and multi-signature scripts the security primitives of time locks and then how we use all of the above bitcoin primitives in order to build simple payment channels then bi-directional payment channels and then time hash time locked contracts and how we put all of these ideas together in order to achieve a routed payment channel network called the lightning network so first of all let's let's quickly review how a bitcoin transaction is structured bitcoin transaction consists of two parts a array or list of inputs and inputs are previously created amounts of bitcoin with spending conditions that are defined in a script that must be satisfied the most common of course being the need for a digital signature that's the most common script which is a very simple bitcoin script and a very simple bitcoin transaction so if you wanted to send money to someone you would take an input that has been recorded on the blockchain you would take its bitcoin script that sets the spending conditions and if that bitcoin script required a digital signature simply a digital signature corresponding to that address you would fulfill it and construct a transaction using those inputs and then you can use that same transaction to produce outputs and the outputs of the actual payments where the money is going so where the money is coming from inputs where the money is going outputs and you can have several inputs and several outputs when you construct outputs in the bitcoin transactions those later become inputs for a future transaction and so on and so forth chaining them all together so in your outputs you specify the conditions that are required to spend that output another important consideration is that in bitcoin transactions any output that you have available to spend must be spent in its entirety you can't spend half of it so another common feature in bitcoin is that if the input you have to spend is larger than the payments you want to make you create a change and the way you create change is by having an additional output in the transaction that returns money to your own wallet or address so those are the transaction basics it's often confusing to people who are due to bitcoin that transactions are structured in this way using this mechanism of inputs and outputs but that's how bitcoin works it's distinct from some of the other blockchains for example ethereum works in a very different way using account balances all right i mentioned bitcoin script and bitcoin script is a scripting language that is incorporated in outputs which defines the spending conditions that must be fulfilled and in order to fulfill those spending conditions you provide the other part of the script and that script is then executed by the bitcoin system in order to verify that you are authorized to spend that output and the bitcoin script is implemented in a language that resembles a rather primitive computer language called forth it is a stack-based programming language which is designed to be touring incomplete so it doesn't have loops and it uses the stack in order to evaluate expressions and if these expressions evaluate to true then the script is considered successfully executed and the transaction has unlocked the input has fulfilled the spending conditions and therefore that can be spent and as i said before the most common bitcoin script is hey show me a digital signature that corresponds to this address and that proves you can spend it and that's called a paid to public key hash i won't go into the details of that you can find it in mastering bitcoin we're going to talk about the different category of scripts today which is multi-sig scripts that are used in the lightning network as well as more complex conditional scripts as we explore payment channels here's a simple example of how a script works and let me quickly switch to full slide mode so you can see it clearly and in this case we have a very simple script and what the script is doing is it is adding the number two to the number three and then it is comparing to see if the result is five so you can use it to do simple arithmetic and this demonstrates how the script is actually executed in this case for example the the portion of the script that says three add five equal might be the spending condition and you fulfill it by adding the number two in front which fulfills this script by satisfying the condition that it should be equal to five if you add it to three a very simple spending condition anyone who can do simple arithmetic would be able to spend a bitcoin output that is locked by this script obviously it's not a very secure script because it only requires primary school arithmetic knowledge and not knowledge of a private key but it demonstrates the function on the left hand side you see a stack and i mentioned this is a stack based language so what happens when you start execution the execution pointer in the script is pointed to the first element of the script which is the constant number two and when a constant value is found in the script it is pushed to the top of the stack so you see that in the top of the stack there's the number two then the execution pointer moves to the number three that is also pushed to the stack now you have two items in the stack the value two and the value three and then the execution pointer moves to the add operand and the add operand pops two items from the stack adds them together as numeric values and then pushes the result back onto the stack so the two and three get popped five gets pushed and that's the result of the add operator the execution pointer then moves to the next item which is the number five that is pushed to the stack because it's a constant and then the execution pointer moves to the conditional operator equal and what equal does is it pops two values from the stack compares them and if they're equal it pushes the result true onto the stack otherwise it pushes the result false once the equal operator has been executed the remaining item on the stack is the value true and if this was a bitcoin script it would be a valid execution of the bitcoin script since the only remaining value on the stack is true and this would authorize spending of the script now when you look at a bitcoin script at first it's a bit confusing because the stack-based operation means that you put the parameters first and the function call next in this reverse polish notation as it's called and it can be a bit confusing to read but once you understand the basic function of how things are pushed and popped from the stack you can get used to this pretty quickly the next thing we need to describe is multi-signature scripts so multi-signature scripts are scripts where the conditions that are defined in the bitcoin script actually require more than one signature and at first this was a built-in function of bitcoin but nowadays it's implemented just using a generic script which has the check multi-sig operator in it so multi-signatures are described as k of n schemes or k of n signature schemes and what that means is that with a multi-signature you define pre-define in fact n valid signatories these are the public keys that are authorized to sign to release funds from this particular bitcoin script and of those n k are required to sign so for example if you say this is a two of three scheme then there are three identified signers any two of which can execute signatures and spend from this address and in current bitcoin in the current bitcoin system n can be up to 15 and k can be any number between 1 and 15 it is likely to be extended to even more signatures in the future the script itself that is actually put on the stack is first the number k which in the example of a two of three script is the number two that is the quorum that is how many signatures are required followed by a list of public keys that are the signatories followed by n which is the number of signatories in total followed by the up check multi-sig operator and this script in order to be valid must be preceded by two signatures or k signatures that that work and right below you see a particular type of a multi-signature script this is a two of two example where there are two signatories that's called an alison bob in the tradition of cryptography names and this script would look like the number two followed by alices public key followed by bob's public key followed by the number two and up check multi-sig this type of multi-sig script requires both parties to sign essentially it's a joint control account where both must sign and one cannot execute this and sign on their own they both must sign in this particular example another security primitive in bitcoin that plays a role in the lightning network is timelocks and timelocks control the spending of bitcoin scripts by setting a future time before which the script is not valid so the script is only valid once that future time is reached this is implemented by an operand called checklock time verify cltv which is a per output timelock that takes one parameter as an input it's either a unix epoch time if it's more than some million numbers or it is considered to be a block height if it's below that so um when you provide a checklock time verify in your bitcoin script the script will evaluate past the checklock time verify operand only if the lock time condition has been satisfied otherwise execution will halt at the checklock time verify and the script will fail with a false outcome so for example if you take the unix epoch now plus three months defined in seconds then checklock time verify afterward this will only validate if that time has passed so you can basically constrain bitcoin spending of outputs through the scripting language to not allow spending before some time in the future or before some block height has been reached and this is also used extensively in payment channels so we'll look at the first example which is a simple payment channel to describe what a payment channel is so payment channels are mechanisms that allow us to construct bitcoin transactions that are not recorded on the blockchain but are secured by the blockchain and this allows us to take these transactions as we say off-chain and off-chain means that these transactions can occur only between two peers without being validated without with the rest of the network but in the same trustless manner that bitcoin supports so that we can significantly increase the scale and capacity of the bitcoin blockchain as well as accelerate the settlement of transactions from minutes to seconds and allow for microtransactions so the lightning network uses payment channels to make bitcoin transactions fast very very cheap and equally secure as the bitcoin network while increasing privacy payment channels rely on a series of bitcoin security primitives and they compose these primitives together using the scripting language in order to create this capability of a second layer above bitcoin that uses the underlying trust from the bitcoin security primitives in order to accelerate and increase capacity for bitcoin transactions so the security primitives that payment channels use are the quorum of control that's a lot that's enabled by multi-signature addresses time locks the ability of the bitcoin system to prevent double spending of inputs the non-expiration capability where a transaction once valid remains valid the never expires and could be presented to the network for execution at any time censorship resistance which means that if someone has a valid transaction they can inject it into the network and the network cannot censor that transaction and in fact it will be executed based on capacity constraints and finally authorization which is the ability to create digital signatures to authorize spending so how do all of these security primitives come together a two of two multi-sig enabling quorum with a time lock is used as the settlement transaction of a payment channel it can be held forever because it doesn't expire it can be spent at any time because it's resistant to censorship and it can be spent by either party once it's signed by both of them through authorization the two parties who engage in this multi-sig transaction can then create commitment transactions that spend the settlement on a shorter time lock and will now explain what all these things mean a bunch of gobbledygook at this point but we'll answer those in detail all right here's a very simple example Emma wants to buy streaming video from Fabian now if you were to do this with a bitcoin transaction or a visa payment or a wire transfer or something like that you either have to pay advance for the video or you have to pay afterwards and Fabian has to trust that the payment will come through also you can't really start streaming the video until you have some confirmation or settlement of the payment using a payment channel instead what we do is we stream video in one direction while effectively streaming money in the opposite direction and the concept of streaming money is critical to understanding what's happening here in the payment channel because we can do very low cost very fast small amount payments we can effectively pay for every second video by updating the balance of the payment channel and sending more and more money to Fabian as Fabian streams a second video and Fabian can simply stop streaming when the payments stop coming so it becomes a utility mechanism for payment every payment corresponds to a second video and neither Emma nor Fabian need to commit to any more than has actually been paid in real time how does this work here we see transactions and in order to help understand how the transactions work they consist of two parts the left part is the input and the right part is the output of the transaction so first Emma constructs a transaction that spends 36 milli bit coin some amount that makes sense for the amount of video that Emma wants to watch and creates that transaction so that that money is deposited effectively into a two of two multi sig between Emma and Fabian that means that once this transaction is sent to the bitcoin blockchain Emma and Fabian must both sign to spend this transaction in order to well to spend this transaction under the multi sig script requirements now this is called the funding transaction and it's the only transaction that is actually transmitted to the bitcoin network on chain and this transaction acts as the anchor if you like or the transaction that opens the channel between Emma and Fabian and with this one transaction the channel has been initiated the transactions that follow are not actually broadcast to the bitcoin network but instead they are sent from Emma to Fabian in return for video and these transactions are called commitment transactions and what they do is they commit a greater and greater amount to Fabian by spending that two of two multi sig in favor of Fabian in ever increasing amounts so Fabian sends the first second of video and Emma in return sends a transaction that signs her signature on the multi sig input and then spends 35.99 millibits to Emma as change and 0.01 millibits to Fabian as the second output once Fabian has this transaction Fabian can at any moment in time if Fabian chooses to do so countersign the multi sig with his signature and this becomes a valid transaction that Fabian can deposit effectively depositing means settling it by sending it to the bitcoin network on chain and once that has happened Fabian will own the 0.01 milli bitcoin output of that transaction because Fabian can spend it and Emma will own the change so Emma has effectively paid now the the part about payment channels that makes them work is that Fabian doesn't need to deposit this transaction they just need to hold it because Fabian knows that they can deposit it anytime they want and the bitcoin network will guarantee that payment therefore they can keep it off chain and continue so Fabian sends another second video and Emma sends another transaction in this transaction Emma let's say has 35.98 bitcoin has changed going to her and 0.02 milli bitcoin going to Fabian then in the next transaction for another second 35.97 to Emma 30 0.03 to Fabian and effectively these act as counters the balance of the funding transaction that belongs to Emma decreases gradually and the balance of the transaction that belongs to Fabian increases gradually effectively what is happening here is that value is being transmitted from Emma to Fabian simply by continuously updating these commitment transactions to share the balance of the channel in a different ratio between Emma and Fabian intellectually or conceptually you can consider this as money moving across the channel in effect no money has moved because all we're doing is writing a new check every time that reallocates the balance between the two channel endpoints and updates it at the end of this what usually happens is that one of the parties either party will transmit a final settlement transaction and the settlement transaction let's say is at the end of this 30 millibits to Emma and change and six millibits to Fabian for 600 minutes 600 seconds of video and that's it once that transaction is settled and either party can settle it then it is recorded on the bitcoin blockchain and so the only two transactions that are ever recorded are the first funding transaction and the final settlement transaction between Emma and Fabian and all of the in between transactions of which there can be thousands or even tens of thousands are not recorded now a bidirectional payment channel works in a somewhat similar fashion but the general construct is always the same which is that let's say Bob and Alice want to create a payment channel they would each provide inputs that they would spend to a two of two multi-sig for which they each own signing keys and they would essentially lock these funds into the two of two multi-sig each corresponding to their own contribution to the payment channel or if you would like thinking of it this way each of which putting balance on their end of the payment channel allowing that balance to go back and forth between them once that funding transaction has been mined on chain and settled then Alice and Bob can spend that two of two multi-sig in a series of commitment transactions that reallocate the balance accordingly so in every one of these commitment transactions they spend it with an output that can be redeemed by Bob and an output that can redeem by Alice by exchanging signatures for the multi-sig and these balances can remain between them in off-chain transactions and they can update them continuously until finally they have a settlement transaction that corresponds to the final balance in the channel after several back and forth transactions now you must be thinking at this point and let me back up a bit you must be thinking what happens if one of these commitment transactions has an advantageous state for Bob and one of these commitment transactions has an advantageous state for Alice where Alice has more balance than she had before but later on the situation is reversed and the balance goes in the opposite direction can't one of these participants simply broadcast a prior state which had a more advantageous balance in their favor and thus basically cheat and steal from the channel well the way this is solved or the way this could be solved theoretically according to the original specification of payment channels is to set a time lock and what the time lock does is it delays the ability to redeem the commitment transaction again these are transactions that have not been committed to the network and they're off-chain but they have been signed with a time lock embedded in them and that time lock prevents either party from spending an older transaction not because they can't spend it because it's not valid they absolutely can but because later transactions become valid sooner so for example here the transaction on the left hand side is only valid after 4,320 blocks whereas the transaction that records a much later state is valid after 3,720 blocks which means that whichever party has the advantage at the end of it based on the balance that they've agreed that represents their actual balances in the channel has an opportunity to spend the transaction on the far right several hundred blocks before any of the previous transactions can be spent as a result they can settle that and once they've settled it that transaction invalidates all of the previous ones because they're all spending the same input they're all spending that single two-of-two multi-sig input and once it's spent unmind on the network all of the other transactions become invalid because otherwise they would be double spending that input so the double spend protection together with the time lock protection ensures that neither party can cheat by spending a prior transaction so this is the basis for payment channels and there's a few other little nuances in bi-directional payments the transactions that are exchanged between the two parties are actually asymmetric meaning that the transactions are constructed in such a way that the transaction held by Irene in this case which is signed by Hitesh allows Hitesh to spend his output immediately but if Irene tries to commit this transaction she will be able to commit this transaction but she won't be able to spend her output until a delay has passed giving Hitesh the opportunity to spend his output first similarly the transaction signed by Irene the Hitesh can commit if Hitesh commits it that gives the opportunity for Irene to immediately spend her balance whereas the output that Hitesh has in the only transaction that Hitesh has that's signed by Irene is delayed by a significant amount of blocks the final component for payment channels is hash time locked contracts and with hash time lock contracts instead of using a digital signature in a multi-sig the mechanism is to have a hash a pre-image and the time lock so to create a hash time lock contract the first thing is the recipient of the payment creates a secret which we call r and then the sender of the payment calculates sorry the recipient of the payment calculates the hash of this secret h and sends it to the sender so the way this works in script is it's an if else statement implemented with the stack language and if you have the secret r then you can present it to this script and once it's hashed and verified you can spend with this secret anyone who has the secret can spend this particular script if the if you don't have the secret you can execute the else clause which gives you a refund after a certain time lock so this prevents funds from being stuck in a channel we use a similar construct in the multi-sig payment channels where there's a refund clause to ensure that if either of the parties simply drops out of the communication system disappears or refuses to cooperate then the other party can simply wait until a refund timeout is triggered and at that point spend the script and get a refund of the money that they locked in the multi-sig so nothing ever gets locked forever there's always a timeout with the construct of a hash time locked script and this concept of payment channels that we've discussed so far we get to the final step that creates the lightning network now all of the examples we've given so far are examples where there was a payment channel between alice and bob and this payment channel allowed alice to send money to bob but if you have to open a payment channel to everyone you want to pay then you still have to do a funding and settlement transaction on this payment channel so you haven't actually saved anything in terms of total number of transactions on the bitcoin network but that's not how the lightning network works the lightning network remember is a network of routed payments over payment channels and what that means is that you do not have to have a payment channel to your final recipient as long as you can find a path constructed by connecting payment channels end to end through which you can route your payment and this is the final example here that demonstrates this concept in this example alice wants to pay eric and in order to pay eric alice does not have a payment channel directly to eric but instead alice discovers a path and this path consists of a payment channel from alice to bob from bob to carol a payment channel between carol and diana and a payment channel between diana and eric because these payment channels exist and because the lightning network allows alice to discover these payment channels alice can construct this path and then route a payment to eric without opening a new channel which means that based on the general idea that if you have a sufficiently connected network everyone will be within a certain number of hops reachable from one end of the network to the other you have a fully routable network so basic payment routing works as follows and this is the final slide i'm going to make it big so you can see it and then talk about it now this slide is annotated with numbers in black which show the sequence of actions that happen in this particular case the first thing that happens is eric constructs an invoice um for alice to pay and this invoice consists of a hash of the secret r that only eric knows and does not communicate with anyone eric um randomly generates a secret r then calculates the hash of that secret and then transmits the hash to alice and that hash tells um alice how she needs to construct the payment this payment is redeemed for anyone who knows the secret r um at the moment nobody knows the secret r except for eric and that way eric will be um the first to redeem this payment now eric can communicate this to alice over any network um a lightning invoice which contains this hash uh and the amount can be transmitted over twitter over skype over text message over whatever you want it's encoded um using a batch 32 encoding um and it starts with the letters l n so you know it's an invoice for the lightning network once alice has the hash um she constructs uh a payment on her payment channel to bob that says to bob if you pay this forward when you have the secret r i will give you this amount bob then constructs another htlc that pays carol and that htlc from bob to carol says if you have the secret r i will pay you this amount um and uh then carol constructs an htlc to diana that says if you know the secret r i will pay you this amount diana does the same to eric if you know the secret r i will pay you this amount now the trick here to understand is that these promises that are being propagated forward from alice to eric are meaningless if no one has the secret r but they also only commit each node in the route um in as much as they receive the secret r from the next hop so for example let's pick bob bob doesn't actually have to pay uh carol and that payment isn't valid until carol reveals the secret r because that's what's required in order to execute that script but the moment carol reveals the secret r bob now has r and therefore bob can now claim equally the htlc from alice so bob isn't making a commitment that puts bob at risk because bob knows that the only way he's going to pay carol is if she has the secret and once she has the secret and has given it to bob then bob can use that same secret to collect from alice and therefore um there's no risk in making this promise now if you think about how the script works if any of the parties was to use the secret r to simply collect the payment and commit that transaction to the blockchain in committing that transaction to the blockchain they would effectively broadcast the secret r to everyone on the blockchain at which point the holders of all of the other htlcs could then just read the secret r off the blockchain and use it to basically to spend the htlcs that are owed to them so there's no way to earn the htlc if you have the secret without also giving that secret to everyone else in the chain therefore allowing closure for everyone so once diana uh sets the htlc to eric eric now knows that um eric can redeem that htlc simply by revealing r to diana so eric reveals r to diana and at that point the htlc is redeemable by eric and eric and diana can update their payment channel to reflect a new balance that puts more value on eric's side which is effectively the payment eric has been waiting for diana on the other hand now has the secret r which means that she can redeem the htlc from carol and when she does so diana receives on her end of the payment channel the value from uh carol updating the balance between them with a new commitment transaction uh but in order to do so she gives the secret r to carol carol now has the secret uh in step eight to give to bob bob has the secret to give to alice and all of the htlcs are resolved and the result is alice has paid eric via all of the other payment channels without having a direct payment channel so that's how it all comes together you'll notice a few little subtleties in here um and there are many subtleties that are not covered by this diagram but first of all one of the things you'll notice is that each of the htlcs has a slightly different amount so alice promised to bob 1.003 bitcoin and bob promised to carol 1.002 bitcoin and carol promised 1.001 uh and diana promised 1 bitcoin so the payment from alice to eric is 1 bitcoin the extra three millibits that are being added to alice's htlc are basically fees and these fees are routing fees so when bob receives 1.003 but only pays out 1.002 effectively bob gains a millibit and that millibit is the fee for bob to do this routing on behalf of alice um the other thing is that in each of these there is a time block which decreases and this allows the final htlc to be spendable before any of the intermediary htlcs to avoid any problems of men in the middle attacks and um finally the way this is constructed is using an onion routed network ensuring that none of the participants really know where the payment is coming from or where it's going all they know is the previous and next hop and they don't know their position in the route therefore enabling significant privacy what that means is bob doesn't know if the payment is coming from alice or if alice is simply forwarding it for someone else um and bob doesn't know where it's going it doesn't know that it's going to eric bob only knows that he has to forward it to carol and beyond that the rest of the route is encrypted if you enjoyed this video please subscribe like and share all my work is shared for free so if you want to support it join me on patreon