Bitcoin ₿ in 100 Seconds // Build your Own Blockchain

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
bitcoin a peer-to-peer electronic cash system first described in a 2008 white paper authored by the mysterious satoshi nakamoto the modern financial system relies on our trust of big centralized banks to hold our fiat currencies and execute transactions but trust is a weakness that eventually requires intervention by lawyers and government bitcoin allows two parties to make reliable transactions based on cryptographic proof eliminating the need for a trustee middleman the optimists call it digital gold the pessimists call it fool's gold but in reality it's just software and like all software its purpose is to arrange ones and zeros in a meaningful way the protocol that makes it meaningful is blockchain which allows two parties to engage in transactions denominated in bitcoins or satoshi's and just like dollars and cents they have value because we believe they do from a financial perspective the blockchain is like a shared public ledger that contains all transactions from all bitcoin users and is distributed and synchronized around the world which eliminates the need for a central authority to maintain and validate it from a technical perspective think of the blockchain as a database structured as a linked list where each record or block represents a group of transactions that have been permanently committed to the database it works kind of like a git repo that can never be rebased the important thing is that each new block is linked to the previous one in the blockchain and its creation goes through a very strict set of cryptographic rules each user or wallet has a unique public key for receiving money kind of like a username and a unique private key for spending money kind of like a password but before you can spend money you'll need to prove that you're the owner of a public key that money has been sent to in the past each transaction contains a hash or encrypted representation of the previous transaction and the new owner's public key the hash is then signed with the previous owner's private key this makes it possible to validate the chain of ownership without the need to expose the private key and the signature makes it virtually impossible to alter the transaction after it's been issued but what if somebody tries to pay two different people with bitcoin at the exact same time or double spend their money that's where mining comes in which is a system that allows multiple computers around the world to agree on the appropriate state of the entire system or ledger each new transaction is broadcast to all nodes in the network the transactions are packaged into a block then miners will expend computing power to validate proof of work they compute a proof for a random problem that is very difficult to solve but very easy to verify the first miner to solve the proof which happens via dumb luck gets a portion of the bitcoin as a reward the block is then broadcast back to all other nodes where it's permanently confirmed on the blockchain this has been bitcoin in 100 seconds if you want to see more short videos like this make sure to like and subscribe and if you really want to learn how blockchain technology works stay tuned because today we're going beyond 100 seconds to build a blockchain from scratch with node.js and typescript and in the process you'll learn all kinds of useful information about cryptography whether you're into cryptocurrency or not there's many concepts in cryptography that you should know about as a developer things like encryption and signing hashing functions and algorithms like sha rsa and md5 that make all this stuff possible over the next few minutes you'll learn about these concepts by implementing your own blockchain from scratch using nothing but node.js and typescript our blockchain will contain wallets where users can send money back and forth each transaction is added into a block then that block is mined with a proof of work system at which point it can be added and confirmed on the blockchain and throughout this process you'll learn about all kinds of important concepts and how they apply to different areas of development to get started you'll need node.js installed on your system then we'll open up vs code to an empty directory run npm init y to create a new node.js project i'll be using typescript in this code because we'll be using object-oriented programming principles to implement the blockchain and having types will just make our code a bit more readable you can install it with npm then create a ts config file and copy and paste the values from the main source code from there we can go into our package json and create a script called dev that runs the typescript compiler with the watch flag to constantly compile our code in the background to plain javascript from there you should be able to run npm run dev from the command line to keep typescript running in the background now we'll write all of our source code in the index cs file at the top of that file we will import the crypto library which is a built-in in node.js as the name implies it's a modular node that handles a bunch of different functionality for cryptography our simple blockchain implementation here has four classes a transaction a block a chain and a wallet let's start by implementing the transaction which is the fundamental purpose of any cryptocurrency transfer funds from one user to another user in a transaction a transaction object has three properties the amount of the transaction denominated in bitcoins or fire coins or whatever you want to call your coin along with the person paying the money and the person receiving the money eventually we'll set up public keys for these users which you can think of as a username that will eventually set as these values in the transaction one final thing we'll do here is add a method to the class to convert the object to a string as we go through the tutorial we're going to serialize everything as strings just to make the cryptographic objects easier to work with and now we're ready to move on to the block implementation a block is like a container for multiple transactions or in our case just a single transaction to keep things simple you can think of a block like an element in an array or more accurately a linked list because each block has a reference or link to the previous block in the chain with the previous hash property and that brings up a good cryptographic question what is a hash a hashing function allows you to take a value of an arbitrary size like say a transaction then map it to a value with a fixed length like a hexadecimal string the value returned from the hashing function is often called a hash or a hash digest when you create a hash it cannot be reversed to reconstruct the contents of the original value but what you can do is validate that two values are identical by comparing their hashes and that's important for a blockchain because it ensures that two blocks can be linked together without being manipulated now to create a hash of a block we're going to implement a getter that will first stringify the object itself then we'll use the create hash function from node crypto which specifies a specific hashing algorithm in this case sha-256 it stands for secure hash algorithm with a length of 256 bits it was developed by the nsa back in 2001 and it's what's known as a one-way cryptographic function which means that it can encrypt data but it cannot decrypt data back to its original form we can use the function to hash the string version of the block then return the hash value or digest as a hexadecimal string and that's all it takes to build a block in this case it's a transaction that has a link to the previous transaction in the form of a hash and it also contains a timestamp because all blocks will be placed in chronological order now we can move on to the chain which again is like a linked list of blocks there should only be one blockchain so we'll go ahead and make it a singleton instance by setting up a static instance property that is equal to a new chain instance that'll just ensure that we have one chain instance instantiated before anything else now we can declare a property for the chain itself which is just an array of blocks in the constructor we'll define the first block in the chain which is called the genesis block the previous hash is null because there's nothing for it to link to then it instantiates a new transaction that transfers a hundred coins to satoshi notice how we're creating money out of thin air here that's no different than when the central bankers or federal reserve turn on the money printer now in the blockchain class we'll often need to grab the last block in the chain so we'll go ahead and create a getter to help us out with that then we'll define a new method named add block that takes a transaction the sender's public key and a signature that we can verify before adding a new block to the chain a naive and simple implementation might look like this we instantiate a new block taking the last block's hash and this new transaction then we push that new block onto the chain but the problem is that there's no way to know that this is a legitimate transaction anybody could send arbitrary transaction data to transfer coin to someone else we can allow people to securely send coin back and forth by implementing a wallet which is essentially just a wrapper for a public key and a private key the public key is for receiving money the private key is for spending money to generate a public and private key we're going to use a different algorithm called rsa which stands for the names of the guys that created it and unlike sha this is a full encryption algorithm that can encrypt data and then decrypt it if you have the proper key to do so to encrypt a value you would use the public key to convert it to ciphertext which is an unreadable version of the original value then you would use the private key to decrypt it back to its original form but what we're actually more interested in is using the key pair to create a digital signature with signing we don't need to encrypt the message but instead create a hash of it we then sign the hash with our private key then the message can be verified later using the public key if anybody tried to change the message it would produce a different hash in which case the verification would fail and that's really important for a coin because if we didn't have a signature then someone could intercept the transaction message and change the amount or change the payee with no way to detect that anything was out of the ordinary now when generating the key pair with node crypto i'm going to format them as strings and to do that i'm going to add some extra options here for encoding the important one to know is the format pem which you would normally save to a file on the user's computer system where it could be reused in the future now that we have a public key and private key we can use it to send money to another user the way we do that is by specifying an amount and the public key of the user being paid we can then use node crypto to create a signature again an sha 256 format using the transaction data as the value we can then create a signature by signing it with a private key this is kind of like creating a one-time password it allows us to verify our identity with the private key without actually having to expose the private key the signature depends on both the transaction data and the private key but it can be verified as authentic using the public key we can now attempt to add that block to the blockchain by passing the transaction the public key and the signature in real life those values would be transferred over the internet then the signature could be verified let's go ahead and refactor the add block method in the chain class it'll use node crypto to create a signature verification then pass the same transaction data to the verifier we can then validate it by verifying that the transaction data has not been tampered with using the sender's public key and the signature itself and we're now able to securely verify that that user is actually trying to spend that amount of money to the other user but there's still one more big issue with our blockchain and that is the double spend issue imagine the spender tried to send money to two different users at the same time they could potentially spend more money than they actually own before their transaction is confirmed on the blockchain the way bitcoin addresses that issue is with a proof of work system which requires each new block to go through a process called mining where a difficult computational problem is solved in order to confirm the block but it's very easy to verify that work by multiple other nodes on the system when mining is distributed around the world it means you have multiple nodes competing to confirm a block on the blockchain and works like a big lottery the winner of the lottery earns a portion of the coin as incentive which motivates people to invest in the computing resources to mine a coin and also to pump the price of the coin higher and higher because the higher the price the more money you make you can think of it like converting cloud computing resources into money now to implement a basic proof of work system we'll go back into our block class and add a nonce value which is a one-time use random number then in the chain class we'll add a method called mine that takes that nonce as an argument what this method will do is attempt to find a number that when added to the nonce will produce a hash that starts with four zeros the only real way to figure out that value is with brute force by creating a while loop that goes digit by digit until we find the requested value to handle the brute force computation we'll create a while loop that creates a hash with the md5 algorithm it's very similar to sha-256 but is only 128 bits and is faster to compute we'll continue to create new hashes inside the while loop until we find one that starts with four zeros when we find it we can return the solution and then send it off to other nodes where it can be verified and the block can finally be confirmed on the blockchain and that takes care of our blockchain implementation if we go down to the example usage here you can see we instantiate a few wallets for different users then allow those users to send money to each other using their various public keys if we go ahead and log out the chain itself you can see we have a bunch of blocks or transactions linked to each other based on a hash of the previous block now this blockchain is obviously not perfect and something that i just hacked together to teach you the gist of how a blockchain works feel free to grab the full source code on github if you learned something in the process please make sure to like and subscribe and consider sending me some bitcoin or sponsoring me on github for just one dollar a fiat per month i use all that income to sponsor other developers myself thanks for watching and i will see you in the next one
Info
Channel: Fireship
Views: 148,487
Rating: 4.9786644 out of 5
Keywords: webdev, app development, lesson, tutorial, blockchain, bitcoin, btc, what is bitcoin, what is blockchain, blockchain js, javascript
Id: qF7dkrce-mQ
Channel Id: undefined
Length: 13min 28sec (808 seconds)
Published: Mon Mar 01 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.