Part 01-Module 01-Lesson 01_Welcome to the Blockchain Revolution

Welcome to the Blockchain Revolution

Part 02-Module 01-Lesson 01_Blockchain Basics

03. Blockchain And Finance-GweF8qN2wfA.en

Hopefully, you had a chance to think about the problem for a little. It will be interesting to see if your ideas are similar to the ideas that a blockchain has come up with. Like we mentioned, the blockchain views the financial system as something that can improve. It started off by trying to replace the banks as a trusted third party. Whether it’s working or not, is something we’re still finding out. What we do know, is that it’s come up with some amazing solutions to a few of the problems that it’s trying to solve. So here we go. First, banks having all this information is crucial, but is it ideal for banks to have complete control over all this data? They have access to everything we do with our money and can choose whether or not they want to share it with us. Maybe it’s better if everyone had access to these records. Instead of having a ledger, maintained by the bank, we could create a shared ledger that everyone has access to. If this were possible, it would allow everyone complete control over their information. Is there a way we could use the shared ledger to establish the same level of security and trust that the banks provide? Here’s another problem that we might be able to solve. Right now, if you want to send money to someone else, banks often aren’t the only third parties that handle it. Whether you use a credit card, PayPal, or Venmo, Snapcash or any other way to send money, you’re giving your information to them too. Now they need to communicate with the banks and they’re also handling your money. This list of companies grows pretty quickly as you try to do more complicated transactions. This can result in delayed transaction times and fees that are collected by the company’s handling your money. The blockchain is trying to fix this too. By creating a shared ledger, the blockchain makes it possible to bypass these third parties. This allows you to send money more quickly and can cut down on the fees associated with making a transaction. So those are some of the problems the blockchain is trying to help solve. You may have had different ideas and that’s fine too. They can adopt being things we cover later on or maybe there’s some problems that you’ll be the first to solve. One thing to note, is that we don’t know yet for sure whether or not this will actually work, but there’s been some amazing progress so far. I’m mentioning that because it’s important to know that this is all a work in progress. It’s not like the blockchain is perfectly figured out as a solution that we’re just waiting for everyone to adopt. Its ideas are still being built, tested and improved. What’s amazing to me is the opportunity we have to be a part of the solution. So hopefully now you have a better idea of the problem the blockchain is trying to solve and some of the core ideas they’ve implemented to try and help solve them. Keep this in mind as we move on to more complicated topics. It really helps to keep things organized in your head to reflect on how they contribute to building the solutions.

03. Financial Transactions-_E5ue8c5iHI.en

Before we get started with the details of the Blockchain, it’s helpful to understand why it even exists. The Blockchain was originally made to try and solve problems that were seen with the way we make financial transactions. In this video, we’ll talk about some of the core ideas behind how financial transactions work without the Blockchain. This will help us better understand the solution that the Blockchain team tries to provide. Later, we can abstract these ideas beyond finance to understand how it can provide the same types of solutions across other industries. So to start, here’s some of the questions the Blockchain tries to answer. What makes money valuable? Why do people use it? Is there a way we can improve the current system? To answer this, let’s break down how the current system works. Pretend we don’t have a way to make transactions at all, our goal is to help set up a system to help people make transactions. To start, we know that everyone has some type of product or service, there are people who need these products and services and there are other people who are willing to give something in return for them. The problem is, there’s no way for anyone to make transactions with each other. So how can we solve this? The first thing you can do is start trading. You’ll have to decide how much value you place in something, and what you’re willing to get in return for it. Once you do that, you’re able to start trading your product with others. This is a great start, but it gets tough because no one really agrees on the exact value for anything. Every trade needs to be negotiated. What we could really use is something that we all agree has a certain intrinsic value, something like gold becomes useful there. If we can agree on how much a certain amount of gold is worth, we can assign each of our products are value based on that, and to take it one step further, we can make a currency to trade in place of that gold. So now we have money. If I want a new game to play, I don’t need to go to the store with things to trade them, I just give them the money it’s worth. Now that we have money, we’ll need someone to track and manage the transactions we’re making. That’s where banks come in. The solutions they provide are exactly what the Blockchain is trying to improve. Keep that in mind as we go through this next section. Banks keep track of our transactions to keep our money safe and secure. They’re what’s known as a trusted third party. That term comes up a lot in Blockchain. A trusted third party is an entity that facilitates interactions between two parties. They help establish the security we need to store our money, and trust our transactions. This is extremely valuable, and what’s really interesting is how they can do it. There are a ton of systems in place that make this happen, but one important tool they use is what’s known as a ledger. A ledger is a record of transaction information. It includes information about who sent money, who received it, when it happened, and how much was sent. Having a record of all these transactions helps the bank do some pretty cool stuff. For one, they always know who has money, who owes money, and how much money exists. They can use this information to ensure trust between people who are making transactions that might not even know each other. This helps them solve what’s known as the double-spending problem. Double-spending is the term for when someone spends the same money more than once, for a financial system to work, this can’t be possible because that person would basically be duplicating money. Banks can prevent double-spending because of the records they keep on their ledger. They know what was sent, and when it happened. If someone tries to spend money twice, the transaction that happened first will go through, and by the time the second one happens, the money will be gone already. The bank knows what time the first transaction happens so they can invalidate later ones. This helps them settle any disputes, confusion or theft that might happen. Since they have all the information, they can decide who is what? So that’s one way to go about solving this problem, and it’s what we’ve done for a very long time. But the Blockchain thinks there could be a different, better way to do this. Before we jump into how they do it, try to think about it for yourself. Is there anything you think could be improved if the system were different? What would that system look like? As a start, focused on how banks use a ledger to help solve the double-spending problem. Is there a way we might not need banks to do this for us? If you’re not sure, don’t worry about it. This is a tough problem. We’re just hoping you get a chance to think a little differently about all this. We’ll spend the rest of this program talking about the answers the Blockchain has to these types of questions. See what you come up with, and when you’re ready, we’ll see you in the next video.

04. Introduction To Bitcoin—Yy2kLko7LY.en

The blockchain got started with it’s first implementation using a new type of currency known as Bitcoin. Bitcoin is a type of digital currency that utilizes the blockchain to help facilitate financial transactions. It laid the foundation for many other ideas underlying other blockchains. Understanding how Bitcoin works is enormous step towards understanding ideas that span across all industries. Because of that, we’ll focus a lot on Bitcoin. In this section, we’ll discuss the history, and development of Bitcoin, and how it helped develop these core ideas. To start, Bitcoin uses the idea of blocks to group and validate transactions. A block is a group of transactions bundled together. This idea is extremely important, but Bitcoin isn’t actually the first time we’ve heard of it. The idea to group, validate, and linked documents actually dates back to around 1991. This was the year that Haber and Stornetta released their research paper titled, “How to Time-Stamp a Digital Document.” In this paper, Haber and stornetta imagined a new way to verify documents. They proposed time-stamping of documents and linking them to the previous document. They explained how this could form a chain of validated up-to-date documents. What Haber and stornetta proposed then would become the precursor to the blockchain now. Fast forward to 2008, when an unidentified author by the name of Satoshi Nakamoto published a Whitepaper. This paper titled Bitcoin, a peer-to-peer electronic cash system laid the foundation for Bitcoin as we know it now. It completely changed how we view and understand currency. On January third 2009, Nakamoto released the Bitcoin software. Unleashing the first Bitcoins into the world. Reviewing this paper will give you a strong foundation in Bitcoin, blockchain, and other types of cryptocurrencies, that we’ll be discussing throughout this program. After this video, we’d like for you to review Satoshi Nakamoto Whitepaper yourself. As you’ll see, the first line already began describing how a peer-to-peer electronic cash system, can bypass the need for a centralized bank. From there, the paper discusses topics like transactions, time-stamps, proof-of-work, networks and many other topics. This paper covers many technical details about how Bitcoin operates, and uses terms and concepts you may not be familiar with just yet. But that’s okay. Try to focus on just a few key questions. “What problem does the Bitcoin try to solve? What solutions has it provided? What components are used to develop this new system?” Since I started exploring the blockchain space, I’ve referred back to this Whitepaper several times. Many of the concepts that Nakamoto wrote about, extend beyond Bitcoin, and even beyond cryptocurrency. These are concepts that are fundamental to building a robust blockchain for any application. As the adoption for the blockchain continues to grow, debate and discussion will continue to run these topics. Throughout these discussions, it’s nice to go back to the source of where it all started, in this Whitepaper. Surprisingly, it was only after Bitcoin was developed that we started to realize the potential of the technology underlying the system, the blockchain. Abstracting these same ideas to applications beyond just financial transactions is how the blockchain was able to begin transforming so many industries. So, take some time now to read through this paper. It will help you better understand the key points underlying Bitcoin and the blockchain. You can find the whitepaper@bitcoin.org/bitcoin.pdf. We’ve also linked down below in the instructor notes. After you’ve taken some time to read it through, let us know your thoughts.

05. Hashing Demo-JZvs3GUgRrA.en

Let’s take a look at SHA256 in action. We’ll demonstrate this using the website anders.com, the website provides an excellent demonstration to show how hash values work. We put a link to the site below the video if you’d like to follow along. When you get to the site navigate to the hash section from the top and you should end up with a screen that looks similar to this. To start, you’ll notice I have a place to input data and a corresponding hash value, what this site does is generate a unique hash using SHA256 from whatever data you type in. Try typing something and notice how the hash value changes every time the data changes, if I type in block chain developer nano degree program I get a hash value. This hash is the unique value for this string of text, if I remove some texts like the word developer, the hash become something completely different. It’s something unique to the new words I wrote. If I type the word developer back into my original texts, I’m back to the original hash. The value for this data will always be the exact same string. If anyone in the world inputs this exact same string they would also get the exact same hash output, but if the data is similar but not exactly the same it will be a completely different hash value. Similar data doesn’t necessarily mean that the hash values will be similar. Changing the data slightly can result in a completely different and unrelated hash value. The only purpose of the hash is to make sure it’s a unique value it is not something to reference if you’re interested in understanding how data is related. That’s the basic purpose of a SHA256 Hash, it’s used to produce a digital identity for any given value of data. Remember this basic idea as we go into blocks, blockchains and more detailed concepts. The hash always serves this one simple purpose that’s true whether we type in data ourselves we get data from somewhere else or the data is an entire block including many transactions. Hopefully this demonstration helps make hashing seem a little more approachable. We don’t need to know many more details than this for now but if you’re interested in learning more, we’ve linked some resources down below the video. Feel free to play around with this tool to help get a better idea of how hash values work.

05. Hashing-o9g3qgOxOZU.en

Now, you have some background on the goals and motivations of the blockchain. Next, let’s walk through how this is translated into the actual components that have been built to make the system work. These components are what’s represented here in the blockchain framework. We won’t cover them in the exact order that listed here, that order has more to do with how the system works together, which we’ll cover more once we’ve defined all the pieces. Instead, we’ll start with what we think are the most fundamental pieces then work up to the more complex components. With that said, we’ll start this video with the topic of hashing. In this video, we’ll discuss hashing and the details of a specific hashing function, SHA256. A hash is a digital fingerprint for information. It’s a unique string of letters and numbers that represent a set of data. To get a hash value, you start with a bit of data and pass it through a hashing function. The hashing function maps a group of that data to a unique hash value. It will take in the information you give it and create a completely unique hash value. This hash value now acts as a unique identifier for the original data. This allows you to identify a given set of data much more easily by referencing its hash value. SHA256 is a specific hashing function. SHA stands for Secure Hashing Algorithm and 256 represents the output of the algorithm. In this case, it tells us that the number you’ll get back as a hash value is a 256 bit number. There are many different hashing functions, but Bitcoin uses SHA256 to create a unique hash value for each block on the blockchain. The reason for this is to create a unique identifier for every block that exists on the chain. This allows us to do some cool things, like references are blocked by its hash value. It even creates the foundation from which we can join blocks together into a chain. To understand how this builds the chain, we’ll need to understand blocks and blockchains a little better. We’ll learn more about these topics next. But first, we’ll walk through a demonstration showing SHA256 in action.

07. Block Demo-3umxfTcJeiw.en

In this video, we’ll give a quick demonstration, of how a block works using the website Anders.com. Let’s navigate to http://anders.com/blockchain. When you get to the site, navigate to the block section from the top and you should end up with a screen, that’s similar to ours. Here, you’ll see a block with a few values; the block number, the nonce, data and the block hash. The block doesn’t have any transactions in it yet but, this all works the same either way. To start, try typing Blockchain Developer Nanodegree Program. Click Mine and it gives you a hash. This hash is just like the one we had before. It’s the result of running all the information through the SHA-256 Hash Algorithm. The difference now is that if we change the data, say by deleting the word Developer, the hash changes and the block turned red. This is just a visual way to show you that this block is no longer valid. It knows that the data no longer matches the original data because the hash value is different. If you change the data back by adding the word Developer back in, the block will be valid and turn green. As you mess around with this, notice a few more things. Each time you click Mine for new data, a new nonce is generated. That’s the nonce we mentioned earlier. Hence the solution to the problem that we’ve talked about. Also notice how the final hash value always leads with a few zeros. This amount of zeros is set by the block difficulty. Finally, let’s see one more thing, you can change the data, say by removing the word Nanodegree, and then click Mine again. This will rerun the mining process to generate a new block, create a valid hash and turn the block green. The nonce is changed and so did the hash. Now that we have a valid block, that starts to get a little interesting. What this means is that it’s possible to change data and update the hash, maybe before anyone notices it even happened. This means you could actually change the data to whatever you like, which is a huge problem. Security measures have been implemented to ensure this doesn’t happen. But it’s an interesting idea to think about. We’ll cover this more later. But until then, try to think about how you might go about stopping this from happening. That wraps up the demonstration on how blocks work. Feel free to mess around with this website more until you’re comfortable with these ideas, and when you’re ready, we’ll see you in the next concept.

07. Blocks-sFgbSgUdJiM.en

Blocks are quite literally the building blocks of the entire blockchain. In this video, we’ll explore what a block is and define some of the important terms related to the blocks. A block is a container that holds a list of transactions to be added to the blockchain. As we’ve seen, a blockchain is a shared ledger containing a list of all records that happen throughout the network. If we were to let this run on forever as one huge list, we’ll end up with an enormous list of transactions. This would get really difficult to work with or manage. To give us more control over this list, the blockchain is split up into smaller sections known as blocks. As transactions are made, they are bundled together into these blocks and added to the block chain. This breaks up the ledger into smaller bite-sized pieces that we can use to manage the entire system more efficiently. Along with these transactions, blocks also hold some other interesting information. Let’s look at the details of a single block more closely. While transactions are held in the body of a block, other information is held in a part of the block known as the block header. This header contains extra information that includes details about the structure of the data inside the block. The hash of the previous block, the time the block was made, the Merkle root, and the nonce all sit inside the blocks header. There were some new terms in there, so let’s walk through them now. The previous block’s hash is what it sounds like. It’s the hash value for the block that comes directly before the given block in the chain. Having this connection links the blocks together by allowing us to always know what block comes before and after any block on the chain. This is what forms the basis of the entire blockchain. The time of block was created is also held inside the header. This way, we know exactly when each block was made. That helps us know when certain transactions took place and can help us catch things like when someone may have tried to spend the same money twice. With this information, we can decide which transactions were valid based on which happened first. This timestamp is the blockchain solution to the double-spending problem we mentioned earlier. The Merkle root, is a hash that represents every transaction inside the block. To get the merkle root, pairs of the transactions within the block are repeatedly hashed together. Each pair results any single hash, then the hash of two pairs of transactions are again hashed together over and over again until you’re left with a single hash value. Given that final hash value known as the Merkle root, you can now reverse the hashing to reconstruct the entire set of transactions from the original block. The nonce has more to do with some topics we’ll cover later related to what’s known as mining. As quick introduction, the nonce is an arbitrary number that can only be used once. When creating a hash for a block, not just any value will work. The system requests a very specific hash value that starts with a certain number of zeros. These extra constraints make the hash more difficult to find. To find that value, you combine all the blocks data with this nonce. To try to generate the correct hash value. Computers guess this nonce over and over again until finally they come up with a value that gives us a hash that meets the constraints. Exactly why this is important might not be so clear right now, but we’ll cover all this in more detail when we go over mining. The number of zeros that are requested to solve this problem is known as the blocks difficulty. If more zeros are needed, that’s need more specific request, so it’s more difficult to find. If you ask for more zeros, block difficulty goes up, if less zeros, block difficulty goes down. Another attribute a block has is known as the block size. The block size is the amount of space a block has to hold information. Like your computer or phone, there are limits to the amount of space on a block. This amount of space in a block is decided by the developer and helps control things like how long it takes for a block to fill up or how many blocks will be on the chain. Once decided, this will be the same for every block on a given chain, and can only be changed by making updates to the software. If the block size were one megabyte, that means that once this limit is reached, the block is full and it’s time to start generating a new one. Another piece of information you’ll find on a block is its hash value. This hash value is a result of running all the blocks data through a SHA256 algorithm. This hash will be the unique fingerprint we can use to identify the block in the future. Remember, if data changes even slightly, this will generate a completely new hash value. That means, if a transaction changes on the block this hash will also change. This is really important because it lets everyone know when a block has been tampered with. This makes the block chain a secure way to keep a history of information that you can be sure hasn’t been changed without you knowing. That’s the basic concept of a block, and some terminology to go along with it. There’s not really more to it than that. Later, you’ll learn how this fits into the system and how you can look through the data inside the block yourself. But overall, this is most of the concepts you’ll need to understand about what a block actually is.

09. Blockchain Demo-NxBnbDlu-mY.en

In this video, we’ll give a quick demonstration of how a blockchain works using the same website as before, anders.com. Follow the link below the video if you’d like to follow along. When you get to the site, navigate to the blockchain section from the top and you should end up on the screen you see here. In this example, you’ll see a visual showing a chain of blocks rather than a single block. Looking at this should all hopefully seem pretty familiar. What you’ll notice though is that there is a new field added to each block shown here as previous. This field shows that each block no longer only contains it’s own hash value, it now also includes the hash of the previous block. By making this association, we’re linking blocks together. This series of linked blocks is what forms the blockchain. Each block in this chain follows the same rules that we learned previously. Each block needs to be validated and we cannot change any data without invalidating the block. So, let’s try it. On the first block type whatever you like. I’ll type blockchain developer nanodegree program. Then click “Mine.” There might be a delay here as you wait for the block to mine. Once completed, you’ll see the block turn green. Now, on the second block type in something new. I’ll try, “I love this course.” Then click “Mine” again. Now, we have two validated block. What happens if we change data in the second block? To test this out let’s delete the exclamation point. This invalidates the block and turns it red just like you’d expect because that’s the same as what happened to a single block. Now, I’ll add the exclamation point back to turn the black green again. But here’s something new. What happens if we change data in the first block? I’ll remove the word program from that block. In this case it invalidates both the first block and the second block. If we had more blocks that reaction would continue up the chain for as many blocks as we had created. This happens because of how the hash values are linked together like we mentioned previously. Let’s see if we can follow the same logic as before, this time for the live demonstration. You’ll hopefully recognize this pattern from before, but I thought it might be helpful to go through it again with this demo. The value of the second block includes the hash of the first block. That hash needs to stay the same for the second block to stay valid. When you change data in the first block, you’re also changing it’s hash. Since this hash is used in the second block it changes the field for the previous hash in that block. Changing any data in the block including the previous hash value makes the block invalid. This small change causes a reaction that keeps running through an invalidating every block in the chain. This visual demonstration definitely helped me when I was first trying to understand blockchains. Try messing around a little more with the data here until you get comfortable with these new ideas.

09. Blockchain-SMoC7Ula0c4.en

As you can probably tell, there’s a lot more behind what makes a Blockchain work besides the Blockchain. Getting accurate information onto the Blockchain is the goal of the entire system, but it’s helpful to understand it as a single component of this larger system. In this video, we’ll go over what a Blockchain is, how it’s created, and some ways it has been made to ensure a secure and accurate dataset. A Blockchain is a shared digital ledger that contains the entire history of transactions made on the network. It’s an accumulation of linked blocks joined together by hash values that have been created over time. All information on a Blockchain is permanent and can’t be changed. This means that the data is immutable. When using a Blockchain, you have a permanent unchanging history of information, which is useful for many different applications. To construct a Blockchain, you need two main things; blocks and hash values. As we’ve seen, every block contains its own hash plus the hash of the previous block. These hash values chain the blocks together in order from the most recent block made all the way to the first block ever created. The fact that these blocks are connected by hash values gives them some pretty interesting qualities. First, we know that if we change the data on a block that it will create a new hash value for that block. That will invalidate the block and we’ll know it’s been changed. But what happens when we look at that block as part of a chain? Well, since the hash for the block changes, it also changes the hash for this block that exists on the next block. This changes the data in that block changing the hash value, and now this gets invalidated too. This change of hash values runs all the way down the set of blocks effectively breaking the entire chain. You can identify any block on the chain by where it is located using its block number. The block number is just the number four where on the chain that block falls. The third block will have a block number three, the second number two, and the first block will be called block number one. The first block on the chain also goes by another name. It is known as the genesis block, and when it comes to the block chain and what it actually is, that’s really it. The system surrounding the development, updates, and ideas about how to best support the chain is where it can get more complicated. As we continue discussing these topics about the Blockchain, keep in mind that the Blockchain itself is just a single component within all of this, where the transaction history is eventually stored.

10. Distributed PeertoPeer Network-PdFkGNGw0Wo.en

When talking about the blockchain, you’ll often hear the network come up. The blockchain is supported by a network more specifically known as a distributed peer-to-peer network. In this video, we’ll cover what a distributed peer-to-peer network is and compare it to some other types of networks. Now a peer-to-peer network is a network of computers that allows information to be shared across users. It allows users known as nodes to send information directly between one another without the need for a central authority to hold that information. So it’s a way to connect users to be able to share information. As an example, think of any chat service like Skype, WeChat or Google Hangouts. These are all peer-to-peer networks that allow you to talk with your friends and Family. If you’re unfamiliar with these apps, you can also think of phones as an example. Phones give peer-to-peer access to anyone else with a phone, and the blockchain is also a peer-to-peer network. This allows us to interact directly with other peers on the blockchain. But the blockchain isn’t only peer-to-peer, it’s also distributed. A distributed network is similar to the idea of a peer-to-peer network. It’s a network that allows information to be spread across many users. So while being peer-to-peer allows open communication across users, being distributed allows that information itself to be owned by those users. To understand a distributed network, it helps to see how it compares with other types of networks. Here, we’ll compare centralized, decentralized and distributed networks. As we talk through these examples, keep in mind that each type of network has its own strengths and use cases. The blockchain is in distributed because that’s simply the best type of network. It’s distributed specifically because it’s trying to avoid being centralized. It’s chosen to avoid the problems it sees with centralizing information in favor of the benefits it sees in a distributed system. In a centralised system, everything connects to a central network owner. This owner can be a person, a company or a database. If there’s only a single source that holds all the information for the system, it’s a centralised system. To help picture this, imagine a library that contains all the books in the world. Anytime you want information, you’d have to go to this library to get it. The information in this case is completely centralized. So this can be very effective and is extremely common way to share information. But what if our library were destroyed? Well in this case, we would lose everything. In a completely centralized system, we wouldn’t have any way to recover this information. Another possible issue could be speed. To get a book, you’ll need to go all the way to the library no matter how far away you might live. To help address some of these concerns, other types of networks have been created. One of these is called a decentralized network. In a decentralized network, there’s no longer a single point where all this information exists. Instead, this information is spread across multiple locations. So instead of holding all our books in a single library, we have many libraries spread throughout the city. Duplicates of each book could exist in each library. Now if our library were destroyed, we’ll lose some of these resources and that’s definitely really sad but we don’t lose all the information. We still have backups of these books in other locations. Here, we could also have libraries spread out and easier to access. Instead of having to go all the way to a center of a large city, you have a library down the street or in your local town. A distributed system is a decentralized system pushed to its furthest limits. In a distributed system, everyone gets a copy of the information with the same access and control as anyone else. There’s no centralization of the information at all. This gives everyone equal access to whatever information that they need. If we extend our library example just a little bit further, we can use it to describe a distributed system. To help imagine it, pretend our library holds 50 books. This is small enough that you could fit them all in your personal bookshelf. So let’s say a whole group of people each get their own 50 books to put onto the personal bookshelves. This will create a network where everyone has quick and easy access to all the information that already exists. This is the idea behind a distributed network. Since we now each have information, we wouldn’t really have much use for the library. But whether it’s library books, data, ledgers or anything else, these core concepts about the way we share information still applies. So that’s the idea behind centralized, decentralized and distributed networks. Now, let’s go back to the blockchain. Why was all this important? It’s important because the blockchain is a distributed network. If a distributed network gives everyone ownership of the information, how do we do this with a blockchain? Here, everyone downloads a copy of the blockchain to their local computer. They interact with this copy of the blockchain and have full access to all the information it contains. This is similar to the library example with everyone having access and control over their books. So we don’t need to go to the library to find them. With everyone having access to the transaction information, we don’t need anyone else like a bank to track that information for us. This distributed system is one way the blockchain is attempting to bypass the need for external third parties. So, that’s how the blockchain operates as a distributed peer-to-peer network. It allows everyone to interact freely with one another on the network, and it gives everyone full access to the transaction histories held on the blockchain.

11. Memory Pool-7oab3_WJUTE.en

On any given network, transactions are happening as quickly as people decide to make them. But that doesn’t mean that the network is able to keep up with processing all of them at once. As the number of transactions being made exceeds the number of transactions the network can process, a waiting line builds up. This waiting line is known as a memory pool. Now, in this video we’ll take a look at the details of the memory pool. The memory pool also known as the mempool is the waiting place for all unconfirmed transactions before they are added to the blockchain. The name comes from the fact that transactions sit in RAM memory of all the nodes in the Bitcoin network. So, what does this mean? Well, when you start making transactions on the blockchain you’ll notice that it doesn’t happen instantly. This is because for a transaction to be complete it needs to be confirmed or verified by the network. Now, this confirmation is done by specialized nodes in the Bitcoin network called miners. By validating transactions before they are added to the blockchain, miners help ensure consensus on the blockchain. We’ll focus on the details of mining and miners later in this lesson. Since there are so many transactions happening, not everything can get picked up immediately. Transactions need to wait in line before they get validated. This line or storage space where these transactions wait is what’s known as the memory pool or mempool for short. Now to better help us visualize the memory pool, let’s jump over to blockchain.info. So, this company offers an online Bitcoin block export service and cryptocurrency wallets. In addition, they offer amazing free online charts, they allow anyone to learn more about Bitcoin stats and market information. Let’s take a look at their unconfirmed transactions view. Now, at the time of this recording there’s about 7,900 unconfirmed transactions all waiting patiently to be added to the blockchain. Can you guess where they’re waiting? Well, if you answered in the memory pool, that’s absolutely correct. So, let’s roll down a little bit and we’ll see a live feed of all the live transactions going on. Now, each transaction is uniquely identified by a hash. If you can catch one of these numbers before they file on biome, you’ll see that this is a string of characters, this one here in the darker line, that’s the transaction hash. The numbers down below it in the lines with the green arrow are the Bitcoin wallet addresses. So, a wallet address is like an email address for Bitcoin. It’s a way for you to tell people where to send money when you’re using a wallet. We’ll go in more depth about wallets later on. In that same line, we can see information about the time, date, and the amount that was transacted. So, it’s all pretty confirmation, right? Now, if you’re interested in checking out more details about the memory pool, let’s head over to the chart section. So to get there, let’s scroll down and navigate to “Products”, “Charts”, and then in charts, let’s head over to “Network activity.” In this section there are a couple of useful charts. Here we see one about the data, about the number of transactions in the memory pool at different times, the rate at which the mempool is growing, and here one about the size of transactions waiting to be confirmed. So, I recommend you take some time to explore and look through some of these charts. So earlier, we discussed the transactions leave the memory pool when a miner has added them to a block. So, miners validate the transactions before they are added to the block and that block is added to the blockchain. This process ensures security and validation on the blockchain. So, now we know how a transaction can leave a memory pool to join the blockchain. However, this isn’t the only reason a transaction might leave the memory pool. Let’s actually take a quick pause to explore some other reasons a transaction could leave the memory pool. So, in the following quiz try to decide which are valid reasons a transaction would leave the memory pool? Don’t worry if this question is a bit challenging, it’s meant to be. Especially since we’re asking you about a topic you haven’t learned yet. So, this exercise is meant to get you thinking about how the memory pool works. So, give it your best shot and we’ll discuss your thoughts afterwards.

11. Memory Pool-V8gpNHVtz2o.en

This was kind of a trick question because all of the list answers are ways a transaction can leave the memory pool. Let’s recap the possible situations. First, if this transaction has been sitting in the MemPool for too long, at the time of this recording, 14 days, it will be removed. In the next possibility, assume all transactions are sorted by fee size with the lowest transaction fee at the bottom. If the memory pool reaches its size limit and a new higher transaction fee is accepted into the memory pool, the transaction with the lowest fee is pushed out of the MemoryPool. So, this answer choice discusses a concept we didn’t cover just yet, fees. Confirming Bitcoin transactions requires a lot of computational energy. That means a lot of electricity bills to pay. Every time a sender puts out a transaction, they can add on a transaction fee. Think of this as a tip for the miner. Not all transactions come with identical transaction fees. Miners can look through all possible transactions in the MemoryPool to see which ones have transaction fees and look at their values. Miners, like most people, like being paid. So, they’ll choose to validate transactions with higher fees. But let’s circle back to the question. If the MemoryPool was reaching its max size limit and a new transaction entered that had a higher transaction fee, then the transaction with the lower transaction fee would be deprioritized and squeeze out. The third choice, that the transaction was included in the block is one that we discussed earlier. Now the reasons transactions wait in the MemoryPool in the first place is in hopes of being validated, then they can leave and permanently be added to the blockchain. Finally, the last entry choice. The transaction or one of its unconfirmed ancestors might conflict with a transaction that was already included in a block. Remember that the blockchain keeps a prominent history of transactions. Once a transaction is included in a block, it’s considered to have one confirmation. As soon as another block is mined on the same blockchain, the transaction has two confirmations. The transaction continues to get more confirmations as more blocks are mined on that same blockchain. Six or more confirmations is considered sufficient proof that a transaction cannot be reversed. So, there’s a 99.9 percent confidence rating that there’s no errors with the transaction that have been added to the blockchain. This means that if the transaction in question conflicts with what’s already on the blockchain, chances are there’s something wrong with it and that transaction will be denied and have to leave the MemoryPool. Now we know some of the ways a transaction can leave the MemPool. But it’s important to know that transactions that have left are always welcome back. For example, when they’re part of the local wallet and get rebroadcast or when they’re received again over the network. Eviction does not imply a transaction is canceled, there is still hope. In this concept, we learned about the importance of the MemoryPool. From there, miners will bundle up transactions into blocks that will be added into the blockchain. We also saw that there are reasons that a transaction might leave the MemPool but not make it into the blockchain. Perhaps the transaction is invalid or maybe it’s timed out. Well, the MemPool is a temporary place to check our work before sending it permanently into the blockchain. Now the purpose of this holding pool is to provide transaction security. Once a transaction is included in a block and that block has been confirmed six times, meaning five additional blocks have been added to that same chain, that block is considered irrevocable as it will require an immense amount of computation to invalidate and recalculate those six blocks. As with many aspects we’ve discussed before, because the purpose of the blockchain is to exist as a transparent, immutable source of truth, the information on it is not checked once, twice or three times but six times to ensure security.

12. Consensus-7dzV9fi_Uew.en

We’ve talked a lot about a block joining the blockchain. But, we haven’t really mentioned how this happens. It starts by the network agreeing on which transactions are valid. This is done using something known as consensus. Consensus is the name for a group of algorithms we can use to create a voting process for the network. This voting process helps make decisions about information on the blockchain. In this video, we’ll look further into consensus starting with the problem that lies at the core of consensus known as the Byzantine Generals Problem. Let’s take a moment and go on a journey back to the early 100s during the rule of the Byzantine Empire in the middle of a war. Stay with me on this. In the end, the relation to the blockchain will be very clear. Nine generals, each commanding a portion of the Byzantine army encircle a city and they need to form a plan to attack it. The generals must only decide, whether to attack or retreat. The caveat is that either all nine must agree to attack or all nine must agree to retreat. If only a portion attack while the others hold back, then they’ll be overwhelmed and lose. In addition, there are some other complications. Of the nine generals, there could be some who were traitors. They may try to disrupt the group vote. For example, if four of the nine support an attack, and another for support a retreat, the final general could have bad intent and mess the whole thing up. To do this, they could send a vote to retreat to those in favor of retreating and a vote to attack to the four who want to attack. The generals are physically separated, and need to send their votes using messengers. These messengers could potentially be captured along the way, fail to deliver votes, or could create false votes. What we just went over is referred to in computer science as the Byzantine Generals Problem. The problem is an analogy for the blockchain network. Replace generals with nodes, and instead of war, think about our blockchain network. The same ideas apply in both situations. In a distributed system, you need a way to ensure trust between users when they don’t have any way to communicate effectively. The solution helps us understand a way to achieve consensus between users who cannot communicate effectively, and have no way to trust each other. It’s pretty neat to realize this problem of establishing trust and a distributed network has gone on for ages. Bitcoin originally proposed a solution to this problem using a proof-of-work algorithm. It’s a way to achieve consensus without a central authority, and is what allows Bitcoin to solve the double-spending problem. We’ll go over the details of this proof-of-work algorithm next.

13. Problems With Proof Of Work-ep3gLqHhnMw.en

A consensus algorithm is fundamental to ensuring a Blockchain remains a trustworthy version of truth. It also prevents any potential adversaries from breaking the system. While this method of achieving consensus has been successful so far, it does have some issues. There are two commonly discussed issues with proof-of-work. High energy consumption and the minor monopoly problem. First, proof of work leads to an extremely high amount of energy consumption. Proof-of-work calculations require a lot of computing power, all this computing comes at a cost both financially and to the environment. To mine Bitcoin, miners setup mining rigs which are high powered computers that process new blocks. Rig can be a dedicated computer design and built specifically for mining, it could also be a computer that was built for something else like a gaming system, but which has enough memory and processing power to perform the calculations needed for mining. People can set up mining rigs in their homes, but there are also mining farms run by larger operations housing hundreds and even sometimes thousands of rigs dedicated to Bitcoin mining. In 2017, one of the world’s largest Bitcoin mines, was located in Inner Mongolia, and it has 25 thousand machines working 24 hours a day to mine Bitcoin. All these mining rigs around the world demand a lot of processing power. Some reports claim that Bitcoin mining, is consuming more electricity than 159 countries around the world including Ireland and most countries in Afrika. At the end of 2017, Global Bitcoin mining consumption, used as much energy as two million US homes combined. And it’s actually possible to use a Bitcoin mining rig to heat your home. The second problem is the minor monopoly problem. Because Bitcoin mining requires a lot of computing power and energy, those who have the resources to access more equipment have an unfair advantage. The diagram here shows the distribution of the largest mining pools around the world. As you can see, it’s a little bit skewed. The mining farms we mentioned earlier actually contribute to this problem, they’ve helped lead to a monopoly of Bitcoin miners that control a majority of the network. Since these nodes dedicate more resources to the network, they have more say in which blocks are considered valid. This causes the network to lean towards becoming centralized, rather than staying distributed like it was originally intended. So that wraps up the issues with the proof of work algorithm. Given these challenges with proof-of-work, other consensus algorithms have been developed to try and fix some of these issues. Coming up, we’ll explore some of these algorithms in more detail.

13. Proof Of Work Demo-rOV8DCcRbFc.en

To help picture what’s going on with proof-of-work, let’s walk through a simple demonstration. For this, we’ll head back over to the website anders.com. We provided a link to the site down below the video. Here we’ll quickly go over what a nonce is, how it relates to block difficulty, and why block difficulty is even important. These are all related to helping understand proof of work, and how it relates to the speed and security of the network. To start we’ll add in some transaction information ourselves. This could be anything, so feel free to add in your own if you’d like. For mine, I’ll say I send Brandy three bitcoin, then Brandy sent two bitcoin to Jessica. These aren’t real transactions, we just made them up. This gives us an invalidated block that we need to find a hash for, instead of clicking “Mine” focus on this number right here. This is the nonce. This is the number the computer is trying to figure out to solve the problem needed for the proof-of-work algorithm. But you don’t need a computer for this, it’s just a lot faster if you have one. Try it for yourself. Change the nonce until the output has one reading zero. Well. Cool, looks like I got pretty lucky there. The problem is I don’t need one, zero, I need four, and that can take a lot longer. This guessing over and over can get extremely tedious, but it’s the only way to solve this problem. This manual random guessing and checking is exactly what the mining computers are doing. The more leading zeros we need, the longer it will take to find the answer. That’s because wanting a hash with more zeros is a more specific request. That makes it less likely that you’ll find a solution, and results in way more guessing. This number of leading zeros requested is what we referred to as the block difficulty. This block difficulty can be changed by updating the algorithm to ask for more or less zeros. You might change the difficulty anytime you want the computers to be able to solve the algorithm slower or faster. In bitcoin, they adjust the difficulty automatically to help ensure a new block is created every 10 minutes. If blocks are created too fast they’ll increase the difficulty to slow the process down. But if they’re being made to slow, they’ll decrease the difficulty to make the process faster. You might wonder, why is 10 minutes important? Having a block every 10 minutes was a decision made by the developers. This 10-minute time was considered a good balance between having a secure network and a network that can actually keep up with creating new blocks. For example, if a block was created once every hour, the amount of transactions waiting to be verified would increase drastically, and the network would be too slow. But on the other hand, if a block could be made every second, then it might allow a hacker the opportunity to change data and free mind the blocks before the network could catch the attack. That’s just a quick summary of why 10 is considered important, this decision can change for different networks depending on what the developers happen to find important. So, that wraps up this quick demo on proof-of-work. Hopefully, now you have a better understanding of how it all works. Coming up we’ll look at some of the issues with this system then look at a few other algorithms that could potentially provide a solution.

13. Proof Of Work-d-jTq7GXynM.en

Proof of work is a consensus algorithm originally proposed by Bitcoin. It’s a solution to the Byzantine generals problem mentioned previously. It’s one of many algorithms that can be used to help reach consensus on a blockchain. In this video, we’ll define proof-of-work, then discuss the details of what makes it all work. The basic idea behind proof of work is that a piece of data can be costly or a time-consuming to produce, but simple for others to verify that work. In proof of work, there’s an upfront cost of resources known as work, put into generating a block’s hash value. This work can easily be validated by the rest of the network to check if it was done correctly. In proof of work, each node is involved in solving a problem meant to prove they’ve done some required work. Having put in the time to do this work is a signal to the system that it is likely able to trust the result of the work that was done. Nodes who attempt to solve the problem are known as miners. Mining to find the solution to these problems can take a lot of computer power. These miners are constantly in a race to solve each problem as quickly as they can to build the next block. In return for their time and resources, they are paid transaction fees that come directly from the users making the transactions. They’re also awarded by the network with Bitcoins that are created specifically as a reward for mining the new block. These new coins that are created are the only way new coins are ever introduced to the system. Let’s look further into the problem these miners are racing to solve. Miners are trying to find the nonce for every new block. We covered this earlier, but here’s a recap now that you have some more context on what it’s for. When creating a hash for a block, not just any value will work. The system requests the very specific hash value that starts with a certain number of zeros. These extra constraints make the hash much more difficult to find. To find that value, you combine all of the blocks data with these nodes to try and generate the correct hash value. Computers guess the nonce over and over until finally they come up with a value that gives us a hash that meets these constraints. Exactly why this is important, might not be so clear right now, but we’ll cover this in more detail when we go over mining. To help you understand what’s going on a little better, let’s jump into a demonstration.

14. Proof Of Stake-MfR6j5IzgP8.en

There are many ways to achieve consensus and different methods are used across different blockchains. One very successful consensus algorithm is known as Proof of Stake. In this video, we’ll cover how proof of stake works, potential challenges if faces, and who’s using it. Proof of stake is a consensus algorithm that seeks to achieve consensus by giving vote to those with stake. Stake in this case means those who have the most investment in a positive outcome for this system. These users are considered the most likely to vote on making a positive impact on or improvement of the system. How does proof of stake work? In the proof of stake consensus protocol, there are no miners. Instead, there are validators. These validators do not need to invest in computing equipment to mine the blocks that create coins because all the coins exist from the outset. Instead, the purpose of these validators, also known as stakeholders, is to determine which block makes it onto the blockchain. In order to validate transactions and create blocks, validators put up their own coins as stake. You can think of it as if they were placing a bet. If they validate a fraudulent transaction, they lose their holdings as well as their right to participate as a validator in the future. In theory, this check incentivizes the system to validate only truthful transactions. In proof of stake, the greater the fraction of the total the coins a validator owns, the higher their chances of being picked to create the next block because they have a higher stake. A validator node with 400 coins will be four times as likely to be chosen compared to a node that only has 100 coins. If a validator’s block is added. The validator is awarded coin to proportional to the amount of their bet. With that said this begs the question, isn’t it possible for a bad acting validator not to lose anything by betting on multiple blocks so they always win out in the end? Very good. You’ve stumbled across what’s referred to as the nothing at stake problem for proof of stake. There’s something about blockchains that we haven’t mentioned before, the possibility for that single chain to fork. When a blockchain is extending under the proof of stake paradigm it’s possible a fork in the blockchain can occur either accidentally. For example, if some nodes receive information to add one block while others receive an update to add another block, or because there is a malicious attempt to rewrite the history and reverse a transaction. In other words, if there are multiple competing block options isn’t it possible for a bad acting validator to just place bets on every block so they always come out on top? It’s true. These are possibilities, but proponents of proof of stake have strategies against these types of attacks. One strategy is a Slasher solution. Which entails penalizing validators if they simultaneously create blocks on multiple chains. Alternatively, some protocols use a strategy that punishes validators for creating blocks on the wrong chain. In this method, validators must be selective and conscious about which blockchain they put their stakes in. Who uses proof of stake? Ethereum is switching from proof of work, to proof of stake in a project code-named casper. Digital cash, or Dash is one of the pioneers of proof of stake algorithm. It’s built on the core Bitcoin platform, but with added privacy and speedy transaction features such as PrivateSend, and InstantSend. There’s also Lisk. Designed to allow developers to create their own decentralized Apps. Similar in function to Ethereum or NEO, but allowing developers to use JavaScript. Lisk uses a customized form of proof of stake called delegated proof of stake. This just means that only the top 101 delegates are able to have stakes in the network, and these delegates are voted on a rolling basis by the community. One Lisk equals one vote. Now, that wraps it up for proof of stake. The next method of consensus we will cover is Delegated Byzantine Fault Tolerance,DBFT for short.

15. Delegated Byzantine Fault Tolerance-QAfmWqaPtSA.en

In this video, we’ll cover another consensus algorithm, what’s known as the Delegated Byzantine Fault Tolerance. We’ll discuss how it works, potential challenges with it and who’s using it. The Delegated Byzantine Fault Tolerance or DBFT is a consensus algorithm based on assigning roles to different nodes to coordinate consensus. Now, how does the Byzantine Fault Tolerance work? DBFT does not have miners. Instead, it has nodes that are split into ordinary nodes and consensus nodes. The majority of nodes in the network are just ordinary citizen nodes that can transfer or exchange assets but, they don’t participate in validating blocks. Consensus nodes has the power to verify each block written to the blockchain. Consensus nodes act as a representative for the other nodes in the network, similar to how an elected government official would represent the majority of its constituents. For an ordinary node to become a consensus node, it usually needs to meet certain criteria which differ from platform to platform. So these may involve owning some special equipment, having dedicated internet connection or having certain stake in the network. Consensus nodes keep track of proposed blocks that could be added to the blockchain. When it’s time to decide which block should be added next, a consensus node is randomly selected from the pool of all consensus nodes. In the neo blockchain, this chosen node is called a speaker and all the other consensus nodes are called delegates. The speaker creates a new block and proposes it to the delegates. Two-thirds of all the delegates need to prove this block before it’s passed. If it doesn’t pass, the chosen speaker returns to being a normal delegate and another speaker is chosen. This new speaker proposes their truth, which block should be added, and this block is put up to vote. If it passes, the new block is added to the blockchain. DBFT is said to be much faster than proof of work and it requires less resources because there are no complicated cryptographic puzzles to solve. Additionally, it’s resistant to forking, because at any given moment, there’s only one version of truth. With that said, DBFT is not immune to problems. Let’s take a look at two potential scenarios. In the first, let’s assume there’s a dishonest speaker. There’s always a chance that the speaker who is randomly selected from the delegates could be dishonest or malfunction, and if this occurs, the network needs to rely on honest delegates to vote the proposed block down so it doesn’t reach the two-thirds approval rate. Since users of the protocol vote on delegates and the speaker is randomly selected from the group of delegates, it’s up to the users to find out which delegates are trustworthy and vote them into power. Let’s take a look at our second scenario. It is up to users who vote on delegates to do their due diligence to only vote honest delegates into power so that dishonest delegates are in the minority. If a minority of delegates are dishonest, the honest majority can vote the block down and the block will make into the blockchain. To help with this, some blockchain platforms release data about the honesty and functioning of each delegate for voters to review. So, who uses the Delegated Byzantine Fault Tolerance? Well, NEO has been one of the biggest advocates for this protocol. It is a blockchain platform in cryptocurrency designed to build a scalable network of decentralized applications. While proof of work and proof of stake are definitely the more popular choices, newer mechanisms continually pop up and prove themselves. Remember that a consensus algorithm gets its reputation from being safe for a long period of time. For example, Bitcoin has stayed a safe network since its inception in 2009. With that said, there is no perfect consensus mechanism and chances are there never will be, but it’s interesting to see newer blockchains coming up with their own mechanisms, and it’s equally interesting to understand their pros and cons.

18. Consensus Algorithms-PiviHjoNU6Y.en

All right, so we just went over some of the fundamental concepts of blockchain and then learned a little more about different consensus algorithms that exist. In the next lesson, we’re going to be talking more about managing transactions and also, I hope if you could just tell us a little more about how what we just learned relates to what we’re going to be doing in the next lesson. Yes, that’s great. So honestly, it all starts with consensus. We need to make sure that on a peer-to-peer network that transactions are approved, right? To be embedded into a block on the blockchain. So, first we went over consensus and the different types of consensus algorithms that we can utilize on a blockchain platform and with proof of work for Bitcoin Core, we now want to look at what the transaction lifecycle looks like as we’re going to embed a transaction into a block. Great, cool. Yes, so next, we’re just going to do a quick recap of the lesson and then we’re going to transition into the next lesson where we’re going to start talking about managing these transactions for ourselves.

19. Lesson Recap-f_4QTzq9eso.en

Congratulations on getting through my lesson. We’ve covered a lot of materials so far and you’ve come a long way towards understanding the basic concepts that make up the blockchain. We put a quick recap of the topics we introduced down below the video. In the next lesson, we’ll integrate these core concepts together to begin building and working with blockchain transactions.

img

Part 02-Module 01-Lesson 02_Blockchain Transactions

01. Lesson Introduction-V9N09N1M70c.en

Welcome to the lesson, blockchain transactions. Previously, we went over some fundamental blockchain concepts and got an overview of some basic terminology. These are important skills for any blockchain developer to understand how to interact with the blockchain. In this lesson, we’ll build upon the knowledge and learn what it takes to manage transactions on the blockchain. This is where the fun happens. We’re going to introduce the blockchain transaction lifecycle, which builds on the blockchain overview from the last lesson. We’ll continue to build on these core concepts to put these ideas into practice by establishing your own identity on the blockchain. By the end of this lesson, you’ll be ready for the first project. You’ll start to manage your own blockchain identity. We’ve put some more details about the lesson down below the video. Read through it if you’d like some more context about the lesson or dive right in and start the first concept. These are some of my favorite topics and I can’t wait to get started. Let’s get going.

02. C1 V4-hokw-eJZ9dE.en

Hi. My name is Balaji Srinivasan. I’m the CTO of Coinbase. Okay, so, why is identity important in blockchain? So, on the one hand, you think of cryptocurrencies being this pseudonymous or anonymous thing, so where does identity comes in? Well, when you use your credit card, the reason that your name is on the credit card is your debiting from your account rather than somebody else’s when you swipe it. So, there has to be some kind of identity match in electronic database and there’s a minus to your account and a plus to theirs. In the same way, when you move cryptocurrency from one address to another, you are effectively presenting a digital signature that shows that you control that address, right? You’re signing a transaction and that shows you have control over the amount of cryptocurrency that’s at this address that you can move it to somewhere else. That signature is itself fact of an identity mechanism. That’s why identities [inaudible].

02. Lesson Motivation-7ZCG1nURsRo.en

Hey, guys. So we just saw an overview of what we’ll be covering in this lesson. So managing Blockchain transactions. So the question is, why is it important to understand how to manage transactions? Well, if you haven’t noticed Jessica, transactions is literally the lifeline of Blockchain. Without transactions, all we have is blocks on the chain, and they’re literally wouldn’t do anything. Like, what purpose would just blocks do without a way to transact and have a storage for data, and transaction literally allows us to manipulate data and transact and that’s what goes into a block on a Blockchain. So it’s extremely important to understand the types of transactions and way we can work with them. It’s a really interesting way to think about it. It’s our way of interacting with the Blockchain. Otherwise it’s just a static entity right there. So with this course, we have associated project so, the Blockchain identity Project. So how or what they’re learning here relate to that project? That too is a really critical question to address. So first, I would like to acknowledge the fact that your Blockchain identity is something that you own. You get to manage, and nobody else can manipulate it, unless if you are given your private key. So something that you get to control. Every time that you transact on a Blockchain, you’re going to have to go ahead and sign that transaction with your private key. So it’s critical to understand your block chain identity. Yes, you bring up some really good points. So with that, let’s actually learn about our Blockchain identity.

03. Blockchain Identity Part 2-nipokUKJNDs.en

We’ll need to make it so that our transactions can’t be traced either. That’s done by creating a wallet address. Our wallet address is made from the public key in a similar way to how the public key was made from the private key. It’s a similar issue, so we handle it in a similar way. This time we run our public key through an algorithm to create the wallet address. Like before, this algorithm makes it possible to find the wallet address from the public key, but not the opposite. Bitcoin uses two different algorithms to make this happen. These algorithms are the secure hash algorithm or SHA-256 and the primitive to digest, or RIPEMD-160. The numbers at the end stand for the length of the output that’s created by the algorithm. 256 means the output is 256 bits and 160 means that the output is 160 bits. Here’s what that process looks like. We start with the public key. From there, we run it through the SHA-256 hashing function. That gives us a unique 256-bit number. Next, we take that 256-bit number and run it through the RIPEMD-160 hashing function. This turns that 256-bit number into a new unique 160-bit number. This number is our wallet address. We can share this unique, secure wallet address without worrying about anyone tracing that back to us or our secure wallet information. At this point, the heavy lifting is done. But we do put this final address through one more step. This step isn’t for security. It’s used to make an address that’s a little easier for us to read. This allows us to share it with others more easily. Right now we’re stuck with a huge ugly number that no one wants to look at. To make something readable, we want it to be a much shorter number. To take it one step further. Let’s even take out numbers and letters that look similar so we don’t mix things up while reading them. That means and a smaller string without zeros, O’s or other combinations of letters and numbers that look the same. To do this, we take the 160-bit number that we got from the RIPEMD-160 and put it through something known as a Base58Check. The Base58Check takes that huge ugly number we didn’t like and turns it into a much smaller ugly number that we can share with anyone. Okay. Now, we finally have our shareable wallet address. That was a lot of information, so let’s review. Our goal was to create a wallet that provides security while allowing us to make transactions. To do this, we started with a private key, which we want no one to see and pass it through an algorithm to create our public key. This public key then went through some more algorithms to create our wallet address. As you can see, this already is getting a bit complicated. The benefit here is that many of these steps are programmed and happen automatically. This allows everything to happen almost instantaneously when compared to the banking system.

03. Blockchain Identity-8uuOHHw2vQI.en

In this video, we’ll learn some more about transactions. We’ll discuss two things. First, we want it so that only someone who owns the money has access to spend it. Next, we’ll want it so that our transactions cannot be traced. And finally, it should also be possible to share this identity with others so that they can make transactions with you. This is all solved in Bitcoin using what’s known as a Bitcoin Wallet. A Bitcoin Wallet establishes our identity on the Blockchain and ensures we’re able to do all the things we mentioned above, it does this using private keys, public keys and wallet addresses. All three of these things are items contained within our wallet. Let’s go over some details of each of these. A Wallet Address or address is a unique identifier for your wallet. This address is a way to identify the owner of a wallet that we can share with others to send and receive Bitcoin. But wait, we’ve seen the details of each transactions added to the blockchain including things like wallet addresses, since we know that the purpose of the blockchain is to be secure, it seems strange that we have our private information available for everyone to see. We need to make sure transactions made with his address are secure and can’t be traced back to us, the good news is, it can’t. But to understand why, we need to take a step back a bit, the reason an address cannot be traced is because of how it’s created. It goes through a bit of a journey starting with private keys and ending with a wallet address that you can share with anyone. Let’s start with private keys, a private key also known as a secret key, is a secret number that allows you to spend your bitcoin from your wallet. These are randomly generated numbers that your wallet creates. Wallets can contain one or more of these private keys and these should not be shared with anyone. Please be very careful with your private keys once you get started with your wallet. The next step is to turn this completely secret private key into a public key. A public key is derived from a private key and gives you a publicly shareable key that cannot be used to spend bitcoin, you can share these public keys with anyone and don’t need to worry about people accessing your bitcoin. What they can use this for is to send you bitcoin. Public keys aren’t randomly generated numbers like private keys are, they are created using private keys in a secure algorithm. Public and private Keys have an interesting relationship to one another, we can share our public key without worrying about the security of our private key. Also, the private key has to be linked to the public key, so that the private key can track the public key. This is really interesting problem to solve with a pretty cool solution. To do this, we use an algorithm that can create a public key using our private key. But after creating the public key, it shouldn’t be possible to figure out what the original private key was. That way we can share our public key with others to receive money without worrying that they’ll later be able to spend money from our wallet. Bitcoin does this with an algorithm known as a one-way Elliptic Curve Digital Signature Algorithm, ECDSA. This algorithm takes in a private key and creates a public key. A one-way algorithm is a term used for any algorithm that’s simple to execute in one direction, but that’s very difficult to reverse back to the original information. In this case, the algorithm can easily create a public key, but given that public key it’s extremely difficult to figure out what the private key was. This allows us to hand out public keys safely while our wallets track transactions using our private public key combinations. Since this algorithm is so difficult to reverse, anyone with our public key won’t be able to figure out our private key. So, this solves one big problem, we have a key that’s safe to share but there’s another problem, this public key can still be traced.

04. Wallet Types-m1lCrrjOPiM.en

Now that we have a better understanding of what’s inside a wallet, let’s focus on the wallets themselves. Because while these basic components like keys and addresses stay the same, there are actually a few different ways these ideas can be implemented. This results in a few different types of wallets. In this video we’ll introduce the major types of wallets and describe their goals, purpose, and functionality. Wallets can be split into two main categories; deterministic wallets and non-deterministic wallets. In non-deterministic wallets, aka random wallets, private keys are generated from random numbers. In deterministic wallets all addresses, private keys, and public keys can be traced back to their original seed words. You can determine the seed of these keys as opposed to a random wallet where you can’t trace things back to an underlying seed. Seed words are a list of words that store all the information needed to recover a wallet. These are generated when you first create a wallet. You’ll see them as soon as you create a wallet for yourself. This type of wallet was developed because it’s much easier for us to remember a set of seed words rather than a list of random numbers and letters. Deterministic wallets are split into two types; the sequential deterministic wallet and the hierarchical deterministic or HD wallet. Of these, the HD wallet is the most advanced form of a deterministic wallet. HD wallets contain keys derived in a tree structure. This means that a parent key can derive a sequence of children keys. Then each of these can derive a sequence of grandchildren keys and so on into an infinite depth. If you look at the structure it resembles a Family tree. In other words, a seed is used to generate a master key. We can generate both private and public keys from the master key. This complexity allows us to manage keys much more easily than we can do in other wallets. Here’s a chart of the three types of wallets and how each generates private keys. Notice that for all of these wallets the private key is very important because this is how we access our funds. In addition, private key generation always uses the secure hash algorithm sha256. Previously, we used sha256 to hash our public key in the process of producing our wallet address. The sha256 algorithm takes an input such as a public key and produces a hash, a unique string of letters and numbers that is 256 bits long. From the sound of this, you’ve probably picked up that private keys and hashing are really important concepts for understanding wallet types. Remember, wallets are an integral part of our blockchain identity that helps us manage blockchain transactions. Let’s explore two of these topics in more depth. First up, private keys.

05. Different Types Of Wallets Deterministic-u3x66kL4AN0.en

Now, there are two types of deterministic wallets. The first are sequential deterministic wallets, and these were first introduced in Electrum. In sequential deterministic wallets, a random number is used to generate a seed. This seed is then put through a mathematical function, the derives a series of private keys. At a high level, the function takes in the private master key that is generated from the seed. It adds in a counter and an incrementing value. Using those inputs, it generates a new private key. So if you have seed, you have all the power, and you can use this to regenerate all the private keys. In a deterministic wallet, the seed is sufficient to recover all the derived keys. Therefore, a single backup at the time of creation is sufficient. The seed is also sufficient for a wallet export or import and this allows for easy migration of the user’s keys between different wallet implementations. Now the second type of deterministic wallet is a fanciest type. It’s the hierarchical deterministic wallet HD wallet. HD wallets contain keys derived in a tree structure. A parent key can derive a sequence of children keys and these children keys can drive a sequence of grandchildren keys, and this can go on into an infinite depth. Both public and private keys can generate this parent-child hierarchy. HD wallets came about in the Bitcoin Improvement Proposal 32 also known as BIP32 and that’s viewable online in the BIP32 GitHub repo. As an aside, BIP stands for Bitcoin Improvement Proposal. These proposals are used to drive improvements to the Bitcoin protocol. Deterministic Wallets can be shared partially or entirely with different systems. Each of these systems can function with or without the ability to spend coins. What does this mean? With HD wallets it’s possible to derive sub public keys from public keys and sub private keys from private keys. This creates what looks like a tree structure. The reason we can separate the generation of sub private keys and some public keys is because of the one-way elliptical curve digital signature algorithm that we mentioned in the last lesson. Remember, we can input a private key into this one-way algorithm and get out a unique public key. But it’s near impossible to figure out the private key if given the public key. Through this one-way algorithm, it’s possible to have a public master key that generates a series of children public-keys. This can happen without knowing the private key. This flexibility provides the option to share parts of the tree structure. This is possible by breaking off a branch and only sharing either the public or private key and only certain levels of it. In application, this is useful for businesses that want to separate out different departmental spending. Each department can break off a section of the tree and generate new keys as they need. But, all the keys still tie back to one main key. In another simplified scenario, imagine a web server is doing content monetization. Each time a user clicks on an ad on a web page, they get paid. In this case, they need one key per page. In other words, each page is a transaction. A web server can share the public key, that is the head of the public branch and derive billions and billions of public keys just from that initial public key. The fancy part of this is that it’s possible to see public information about these transactions if you know the public key. But, the private key which is used to unlock sensitive data need never be revealed or come in touch with the server. This becomes a trustless server. HD wallets allow for quite a bit of flexibility. They allow sharing of only parts of a bigger tree structure. Ensuring separation of the public or private sublevels. However, the downside is that HD wallets require a strong backup of that master key and this is because everything else is derived mathematically from that master key which puts a lot of risk on it. What’s important to take away from this discussion is the differentiating factors that make up each type of wallet and what makes you unique. Each while it has its own use case. Wallets continue to evolve depending on situational use cases that arise. So it’s important to know the advantages and disadvantages for each type. No one type of wallet fits all situations. To help you submit the characteristics of each of these three wallet types, try your hand at the questions below. You’ll have a chance to figure out which of these wallet types is best suited for which scenario.

05. Different Types Of Wallets Non-Deterministic-rQRIoyEkxg0.en

So far, we introduced three types of wallets: non-deterministic wallets, sequential deterministic wallets, and hierarchical deterministic wallets. Now, that we understand hashing and private keys better, let’s return to these wallets and discuss how they’re generated and when to use each type. First, let’s focus on non-deterministic wallets. Non-deterministic wallets were created during the first implementation of Bitcoin client. These are random wallets, which means that the keys are generated randomly, and there’s no way to determine how they were derived? Non-deterministic wallets can be thought of as a collection of randomly generated private keys that have no association with each other. In short, a random number generate a private key, which is used to generate a public key, which gives us the wallet address. For privacy, it’s best practice to generate new wallet addresses for each transaction. So, no one can track links between the addresses. Now, based on this logic, every time a new key is generated, you need to backup the wallet, so as not to lose the newly generated private key, and this seems like quite a chore. So, why even bother with non-deterministic wallets. Well, there are situations where wallets might be generated for backend services, using private keys that are not derived from a seed. The opposite of non-deterministic wallets aka random wallets are deterministic wallets. In a deterministic wallet, all addresses, private keys, and public keys can be traced back to the original seed. So, there’s a purpose behind each of these IDs and nothing is random, because they can be determined. So, deterministic, determined get it?

06. Generate Private Keys-EFx5Rhbplew.en

We just covered that private keys generate the public keys and wallet addresses that allow us to interact with the blockchain. For a private key to be secure, we need to use a cryptographically secure random number generator that ensures a private key we create cannot be easily traced. And in this section, I’ll show you how to use a Bitcoin address generating website, that uses your operating systems underlying random number generator to produce a 256-bit Random Number. One popular website is bitaddress.org. This isn’t open source JavaScript client-side Bitcoin wallet generator, it’s an online service that helps you generate a random Bitcoin address and associated private key. To be secure when generating a private key, I suggest that you do this offline. This way, all the activity you do is local to your computer and cannot be traced online. So to do this, in the browser, first choose “Save page as”, and save the file to your computer. Next, disconnect from the Internet. Now, open the bitaddress.org.html file that you saved. This is when bitaddress will generate a random set of keys. To do this, it all requests your help to really spice things up, and add a little entropy. You’ll move your mouse around the screen and bitaddress will sample the mouse coordinates to contribute to the number generation. Alternatively, you could type some random characters into this textbox here, and we’ll use those values instead. Once your wallet has achieved full randomness, it will spit out a Bitcoin address and a private key as well as their related QR codes that you can share with others. Now if none of the methods I’ve shown you strike your fancy, remember that software wallets such as electron will generate private keys for you. Let’s jump back into electron, and see where we can find private keys that it generated for us. From the addresses tab, we can see a list of Wallet addresses. To see the associated private key, right-click on the address and navigate to reveal your private key. Now remember, be very careful and do not share this information. The wallet I created here is only for learning purposes. What if you’d like to view multiple private keys at the same time? Another method to view addresses, from the view here, is from wallet, navigate to private keys, and they go to export. Here, you have the option to export a list of all your wallet addresses and their associated private keys, in either CSV or JSON format. You may be wondering, well, if the private key is supposed to be so private, why are there options to reveal it? So it’s possible that you may need to restore your wallet for a number of reasons. This is a time that you might need to access your private keys, but be very cautious when handling this information. Now that it wraps it up for the private key section. To recap, we learned that wallets store private keys. These private keys in turn generate public keys and wallet addresses that allow us to interact with the blockchain. Private keys are nothing more than a random number that’s between one and two to the power of 256, a number that’s so big, it’s near impossible for the same two private keys to exist. Lastly, we saw three different ways to generate a private key. There’s the old flipping of coin method, we could use a random number generator, that’s provided by industry bedded library, or we could use a Bitcoin address generating website. Give the following quiz a try and generate a private key on your own.

06. Private Keys-VLAQvzBBWqQ.en

We’ve seen that there are different types of wallets and that wallet addresses depend on private keys. Private keys generate the public keys and wallet addresses that allow us to interact with the blockchain. In this section, we’ll explore the purpose of a private key, what makes them secure, and then explore different ways to generate private keys for your wallet. So let’s get started. A private key is just a number, a 256 bit random number between one and two to the 256. It can be represented in a number of different formats, all of which correspond to that same 256 bit number. You may see this number presented in a number of different formats and don’t be confused, it still that same number. Now, a common way to represent a 256 bit private key is in hexadecimal format, 256 bits in hexadecimal is 32 bytes, using 64 characters from the range is zero to nine and A through F. Other common formats you may come across are the wallet import format or WIF for short or the WIF-Compressed format. Both of these are ways of encoding a private key so as to make it easier to make different copies for different use cases. But remember, these all represent the same number. At this point, you might be wondering how is it possible that every private key is completely unique? Remember, a private key can be any number between one and two to the 256, so the number is huge and it gives us an incredible amount of possibilities. Let’s take a minute to put that into perspective. There are about two to the 63 or seven quintillion grains of sand on planet Earth. Not even close to the two to the 256 possible private keys. So, there seemingly infinite number of private keys available. How do we get one? Well, the exact method you choose doesn’t matter as long as it’s random and not repeatable. It’s actually as simple as grabbing a coin, a pencil, and a piece of paper. If you flip the coin 256 times and write down one for heads and zero for tails, the resulting number is a binary form of a random private key and you can use it in your Bitcoin wallet. If you want to go about it programmatically, you’ll need to find a source of entropy. The definition of entropy is a lack of order or predictability is the degree of disorder or randomness in a system. In other words, we’d like to find a random number generator. However, it can’t just be any random number generator, it needs to be very, very secure. So, it is essentially impossible to trace how we generated the number because if we could trace how it’s generated, a hacker could easily generate our number and gain access to our private keys. We’ll need to create a cryptographically secure random number generator. If you’re tempted to create a random number generator on your own, don’t do it. Creating a cryptographically secure random number generator is by no means an easy task. Even cryptographic experts have a hard time creating ones that are unhackable. So, do not try this by yourself. Instead, use an industry establish properly peer reviewed and vetted cryptographically secure random number generator. Most operating systems have a source of entropy or a library with a cryptographically secure number generator. For example, Python has the random library and Java has the secure random class. Alternatively, there also a Bitcoin address generating websites. They use the underlying operating systems random number generators to produce a 256 bit random number. In the next video, I’ll demo how to use such a website to help us generate private keys and wallet addresses.

09. Signing a Transaction-qZnId93SXDk.en

We know a wallet can help us make transactions and it can manage many transactions, how do we ensure that we can trust a transaction that is listed in our wallet? This is done using a signature. A digital signature establishes a proof of ownership for each transaction on the blockchain. Earlier, we discussed wallet types and management of private and public keys. We discussed the process used to secure wallet address ownership, the various ways to manage private and public keys and how this relates to wallet security. We also discussed how the wallet process establishes trust. Wallets however are only a part of the equation. We must also ensure that transactions are secure. Why would somebody trusts a transaction on the blockchain? The transaction starts broadcasting to the network when a wallet first signs the transaction. Like a pen and paper check, Bitcoin requires a signature from the sender before the transaction is submitted to the network. In Bitcoin, this is done using a digital signature. So, how does this proof of ownership help establish security on the blockchain? Well, imagine if sending Bitcoin were easy as sending an email, what’s stopping a thief from sending your Bitcoin to other people? That’s what signatures are for. They ensure that it’s actually you who’s sending Bitcoin by signing the transaction with your own personal identity. This signature is created using a Bitcoin wallet address. The wallet address is similar to a bank account number. It’s a unique address that belongs to you. This wallet address is linked to a private key. So, instead of a signature on a paper check, you’ll use your private key to perform a transaction. Once a transaction is signed, it goes from the sender to the receiver as a transaction message. In Bitcoin, the transaction message is broadcasted to the chain as an unspent transaction output known as UTXO. Only these unspent transaction outputs can be used as inputs to an accepted transaction. Each of these unspent transaction output contains conditions regarding the proof of ownership to transact with those funds. These proofs of ownership are derived from your private key. Let’s break this down by starting with transaction inputs. Transaction inputs are considered inbound payments that contribute to funding your wallet. Imagine, you have a wallet with a zero balance and want to send Bitcoin to your friend. The first problem you’ll encounter is a lack of funds. You’ll need to fund your wallet and perform a transfer of value using transaction inputs. To get these funds, you can obtain them from several sources at different times. Each transaction that is transferred to your wallet is considered a new transaction input. Each transaction input has a condition. The transaction input will need to be converted to an output which contains the condition to prove ownership using your private key. With your private key, you can sign your transaction with your digital signature proving you own the address containing the transaction inputs. A wallet must contain funds to be able to produce valid transaction outputs. This allows you to transfer value on the blockchain to your friend. Let’s imagine that your wallet obtained three transaction inputs with the following values 0.25, 0.45, 0.33 of a Bitcoin, your wallet is now worth 1.03 Bitcoin. All right. If you obtain three transaction inputs, creating a total value of 1.03 Bitcoin, how do we make sure to pay your friend, pay the transaction fee and obtain 0.027 bitcoin change back? Now, that’s a great question and is the idea behind transaction outputs. To create a transaction output, you need to have the sum of the transaction inputs which are equal to or greater than the value you are sending, Next, we will include the miners fee into the outbound transaction. Remember, that miners transaction fees motivates miners on the network to include your transaction into the next block on the chain. Basically, any amount greater than one bitcoin will go to the miners transaction fee. Depending on the organization of your transaction inputs, you might be transmitting more value than you prefer. In the case of you sending one Bitcoin to your friend, you would expect to get changed back. Good news, we can do that. Just like the way we created a transaction from you to your friend, we could create a new transaction including outputs for change to be returned back to you. Here, you would create a transaction output,1.003 to your friend. This output includes miners transaction fees of 0.003. The remainder of your input transaction will now be configured as a new output for change which will return 0.027 Bitcoin back to your wallet. Now that we understand how a transaction works, utilizing you UTXO, the next step is to transmit this transaction be included in the blockchain mempool. To recap, you learn the purpose of proving address ownership by signing a transaction with your private key. Finally, you learned how transaction inputs and outputs have conditions called proofs. These proofs are valid unspent transaction outputs known as UTXO to transfer value from one wallet address to another. These are all extremely important concepts that allow users to trust a transaction on the blockchain.

10. Blockchain Transaction Lifecycle-Emrprht-SqY.en

All right. We’ve covered a tone of information and congratulations on getting this far. In this video, we’ll walk through the blockchain transaction lifecycle. This lifecycle follows the journey of a single transaction as it works its way through each stage in the process towards joining the blockchain. This will bring everything together that we’ve learned so far and establish a framework that we can use to understand the entire process. Keep in mind everything that you’ve learned throughout the previous lessons, because this lifecycle spans all of it. This will hopefully provide some clarity on how all the pieces fit together. Here’s what the lifecycle looks like between two BitCoin users, Joe and Brandy. In this example, Joe wants to send one Bitcoin to Brandy. First, Joe gets Brady’s wallet address. Using this information, he creates a new transaction for one Bitcoin from his wallet and includes a transaction fee of 0.003 Bitcoins. Next, he verifies his information and sends the transaction. His wallet starts the transaction signing algorithm which signs his transaction using his private key. The transaction is now broadcasted to the memory pool within the network. This transaction is eventually accepted by the miners. These miners group this transaction into a block, find the proof of work and assign this block a hash value. This block is now placed onto the blockchain. As this block gains confirmations, it is accepted as a valid transaction in the network. Once the transaction is accepted, Brandy finally gets her Bitcoin. If you understood most of all of that, you’ve come in an enormous way towards understanding the blockchain. This concise summary obviously doesn’t include all the details, but acts as a quick story that you can use to branch off into more of the details we discussed through the lesson. Congratulations again on getting this far. We’ll definitely be using all of this as we dive deeper into each of these concepts later on.

11. End Of Lesson Motivation-dIefxRIqwRs.en

Hey guys and welcome back to another segment of Block Talk with Brandi. And so, in this part, we’ll be asking- we just covered a lot about the transaction life cycle, we’ve been focusing specifically on Bitcoin. I’m just wondering how did these principles apply and do they apply to other block chains? Absolutely, so, anytime that you establish identity on a block chain you need to manage that identity and as you notice it’s backed by your private and public key, and you want to really keep that private key secure. So, the same principles that all of us have learned throughout the lesson is applicable on almost any platform that deals with block chain technologies. You still have an identity, it needs to be managed, and you want it secure so if there’s anything that we’re trying to get out of all this is the power of keeping your identity secure. Nice. That’s a very key point to take away and I thought the power of what we’re learning is universal. So with that, let’s take it to the course recap.

12. Course Recap-BQ7aTS0Gpu8.en

Congratulations. You’ve made it to the end of the course. This course is a huge first step in your journey to becoming a blockchain developer. Throughout this course, we discussed fundamental concepts underlying the blockchain and got started managing your identity on the blockchain. Our goal was to get you comfortable with these new ideas and to prepare you to complete your first project, where you’ll begin managing your own blockchain identity. At this point, you’re ready to go ahead and complete the project. We’ve provided a quick summary of everything we’ve covered so far down below the video. Take a minute to review this if you like, and when you’re ready, go ahead and get started on the project. We’re excited to see your submission. And when you’re done, we’ll see you in the next course.

img

Part 02-Module 01-Lesson 03_Verify Message Signature

img

Part 02-Module 01-Lesson 04_Manage Your Blockchain Identity

media

Part 03-Module 01-Lesson 01_Blockchain Data Overview

01. Lesson Overview-NtqXqLLQyVI.en

Welcome to the lesson. We’ve covered a lot so far and we’re ready to go over more details about the blockchain as a dataset. In this lesson, we’ll talk about the blockchain dataset, it’s use cases, and how it compares to other types of datasets. You’ll explore a blockchain data and get a few more tips on how to work with in. A lot of the data ideas we talked about earlier, are really going to help here. These new concepts put you on the path towards completing project too. Where you’ll create your own private blockchain. To get you started, we’ve put a summary of what we’ll cover throughout the lesson down below the video. Take a minute to look through this and get a better idea of topics we will cover and how you’ll start to apply them through the lesson. Once you’re ready, move on to the next concept. We’ll see you there.

02. Blockchain As A Dataset Motivation-7AO1iNN8lp0.en

Hey, I’m sitting here with Brandy and we’re about to get started on this next lesson. So, I want to ask you a couple of questions real quick, before we get started. Throughout this lesson, we’re going to be talking about the blockchain as a dataset and comparing it to traditional databases and I was wondering if you could explain why that’s an important thing to even understand? Yeah, that’s an excellent question. So, right now, we have traditional datasets that we’re all comfortable with. With blockchain, it’s a new way to look at a dataset. It’s immutable. So, we’re going to look at the fundamental difference between traditional datasets and blockchain datasets. So, we can actually start working with it. Yeah, there’s definitely certain limitations that the blockchain has, but there’s some incredible things that it can do. So, it’s great to hear how we can compare it to traditional database. Another thing I was wondering is in this lesson, we’re taking a step back, still I’m talking about conceptual things rather than really diving in and starting to program and I was wondering if you had any insights on why it’s important that we really understand this before we move ahead? Without a doubt, there’s some differences and we need to understand those fundamental differences. So in this lesson, we’re really hoping to set the fundamental values of blockchain as a different means of a dataset that we’re going to work with. After all, the goal here is for a decentralized ledger that is replicatable amongst nodes, right? Peer to peer network. So, a lot of different ways of working with this dataset, this can just take just a little bit of time to understand those fundamentals. All right, thanks Brandy. So, keep that in mind as we go through the rest of the lesson. Next, we’re going to start off by comparing a blockchain to a traditional dataset. So I’ll see you there.

02. C2 V6-ISnRh5HXFkI.en

So, when people talk about blockchains, probably the best single sentence in order to encapsulate what they do is they are tamper-resistant databases for storing things of value especially in an adversarial environment. You don’t want somebody to randomly be able to write themselves a million dollars. You want to make it difficult and expensive for them to do that, maybe so expensive that it would be easier for them to make a million dollars honestly than to write themselves a million dollars in this database, and that’s the fundamental problem the blockchain solve. So, among other things, since you don’t want just anybody to be able to write themselves that data, you want it to be decentralized, you want the power to be spread out a bit rather than one actor being able to write themselves a million bucks. Once you start thinking about the requirements for database to represent money or money-like thing, you start to get to the phenomena that we observe in blockchain. So, decentralized, immutable, and subject to global consensus.

03. Blockchain Characteristics-9DAIl0tfzyw.en

Blockchains, like a traditional database, are a way to store data. You can think of them as a dataset with specific characteristics. In this video, we will compare the characteristics of a Blockchain to those of a traditional database. To start, let’s look at the network. Unlike traditional databases that rely on a centralized authority, blockchains are supported by a distributed network. Blockchains allow anyone to download a copy of the database for themselves. This gives them full access to the data and functions available to the database. A benefit of this is that no single entity can regulate the data that exists on the database. A downside to this is that there’s no central authority to help dictate what information is accurate. The distributed network was made as a way to reach consensus on the accuracy of data without the need for this authority. As we’ve seen, the consensus algorithms involved with this can be pretty complicated and results in other issues like network speeds. Next, there’s different functions available to users on a Blockchain when compared to a traditional database. While in a traditional database, users can create, read, update or delete data, in a Blockchain, they can only read, append or validate data. A major difference to note here is that Blockchains do not allow users to delete data. Rather than deleting or overriding all data, Blockchains create a new record. For example, in a Bitcoin transaction, let’s say Brandy has 10 Bitcoin in her wallet. The transactions that lead to this balance are permanently stored on the Blockchain. If Brandy gives me four Bitcoin, that transaction is also recorded on the blockchain. Brandy’s new wallet balance will appear as six Bitcoin. The transactions that lead to her original balance of 10 Bitcoin are still not wiped out. They’re recorded on the Blockchain along with any future transaction information. Since you can’t delete Blockchain data, the database is considered immutable. Immutable is the term used to describe any data that cannot be updated after being added to the database. The benefit of this is that the Blockchain maintains a permanent historical record of all transactions that have happened on the network. If there’s any dispute over a Blockchain transaction, there’s always evidence to go back and check. The downside to this is the immense amount of memory space and resources that are needed to store this dataset. Next, the way authorization is handled on a Blockchain is much different than in a traditional database. With a Blockchain, authorization isn’t controlled by any central authority. Every user on the network has equal access to data and functions available to each of the users. While both types of data are very secure, the access you can gain from a single point of authorization is drastically different. Once you have the appropriate credentials, you can gain access to any type of database. The differences on a Blockchain the best you can do is get the credentials of a single user, and even then you can only access their personal data. With a traditional database, if you get authorization for the database, you just got access to the personal data of everyone in the system. For that reason, we consider data on a Blockchain to be more secure. But this type of security does come with some downsides. For one, without having a central authority and control, it’s difficult to resolve disputes that might come up. With a Blockchain, you can’t call a company to fix something you disagree with. The security is entirely handled by software running the system. The systems that help maintain Blockchain security exists to facilitate the fact that a Blockchain is highly transparent. As we mentioned previously, anyone can access the same data and functionality provided to anyone else on a Blockchain. This is in contrast to a traditional database where this permissioning is controlled by the authority that owns it. We consider this open access to be an upside to the Blockchain solutions because that’s exactly why it was created in the first place. One potential downside to this is that you won’t have a careful permissioning system like on a traditional database. To recap, we just compare the differences between the network, functions, mutability, security, and transparency of each of these database solutions. We tried to avoid making judgments about which is better because that’s not really the point, neither of these solutions is better than the other. Overall, they’re only better or worse in a given situation. There’s also many other ways these databases could be compared. Things like the ease of use, integration with existing technologies, and other important characteristics can definitely come into play here. These are just some of the basics to get you started so feel free to dig deeper into these ideas if you’re interested in learning more. Hopefully, this is a good starting point for you. Understanding these differences will help you decide when an application is best suited for the Blockchain and when it isn’t.

03. Traditional Database Characteristics-2dqPMp3dYQA.en

A database is a collection of information organized so that it can be accessed, managed, and updated. A blockchain is a type of database. But how do you know when a blockchain is the right type of database and when it might not be the best solution? To start, it helps to understand some of the core characteristics of a traditional database. In this video, we’ll look at the basics of a traditional database using five basic characteristics. We’ll discuss the basics of the network, functions, mutability, authorization, and transparency of the traditional system. With a better idea of how a traditional database works you’ll be able to more easily compare it to a blockchain. First, how does the network of a traditional database operate? Here, data is stored and maintained by a central authority. This authority collects, manages, and owns this information. To get access to the data users need authentication from the database administrator. Let’s use an airline as an example. In this case, the airline is the central authority that collects and owns the data. To access this information you’ll either need to work with the airline or get authentication to access the information through something like their website. Once having permission to access the database, there’s a few functions available for you to work with in the data. A traditional database allows for four basic functions; create, read, update, and delete. These functions are called CRUD for short. These give users the flexibility to not only retrieve and add new data, but to remove and change data as well. This provides a lot of flexibility for the database. For the airline, a benefit of this would be that they can do things like create new flight records or update existing ones. The functions available on a traditional dataset are set up so that the data is mutable. Data being mutable means that the records can be updated after being added to the database. This could be helpful in the case that an airline no longer offers a particular route. They can delete this data to ensure it doesn’t show up in customer searches. This is useful, but there’s also a potential downside to this. A flight could be deleted accidentally or even deleted on purpose by someone trying to hurt the system. There’s usually security to ensure this doesn’t happen, but it’s definitely possible. Next, let’s look at how authorization is handled on a traditional database. The central authority that manages the database is also in charge of handling it’s authorization. The airlines needs can influence how they decided to structure their database and who they give access to. Users of this system rely on the security infrastructure set up by the airlines database administrators. One way the data is kept secure is by managing the transparency of the information. In a traditional database, the authority in control of the data grants permissions to it’s users. They have complete control over permissions for each of the CRUD operations we mentioned. Maybe you can create data by booking a flight but you can’t delete it without calling the airline first. This all depends on the permission level set by the authority in charge of the data. Since by default all the data is restricted, traditional databases are considered to have a low level of transparency. That wraps up this basic overview. To recap, in this section we discussed five characteristics of a traditional database. We now know that the network is dependent on a centralized authority. The functions available on the database are to create, read, update, and delete known as CRUD. These operations allow you to make changes to the data which means that it’s mutable. Security is completely in the hands of the central authority that owns the data. Finally, these databases are generally not very transparent. This is a pretty high level overview but hopefully it gives you enough to have some intuition on when a traditional database could be used as an effective solution. Next, we’ll look at how these characteristics compared to that of a blockchain.

04. Do You Need A Blockchain-4sLaQlt4kN8.en

As you’ve seen, there are many differences between traditional databases and blockchains. Neither solution is best for every situation. It’s helpful to understand when you would use a blockchain, and when it’s not actually the best fit. In this video, we will focus specifically on blockchains. We’ll go over a set of questions you can use to help decide if the blockchain is the right database solution for your needs. To get the most out of these questions, think of an example where you might want to use a blockchain. Consider a use case or application that you’re building, we’ll walk through these series of questions to figure out if a blockchain is the best solution for your example. Here are the five questions we need to answer, saying yes to any of these doesn’t necessarily mean a blockchain is a good solution. But if you can answer yes to all of these questions, then a blockchain is likely a great solution for your application. Let’s walk through them, one at a time. First, does the application need a database? This is a pretty broad place to start, but it’s important to make sure that you’ve thought through the use case of your application. If you don’t need to store data in a database, then you don’t need a blockchain, and you actually don’t need any type of database for your application. So next, will the application required shared write access? What this is asking, is if a collection of users will need access to add or write to the database. Internet and cloud-based applications commonly have shared write access. Something like Google Sheets was originally meant as a shared access spreadsheet, where Excel was more of an application to use on your personal computer. If your application requires this type of shared access database, you can select yes to this question. Third, do you need to create trust between users? With a blockchain, you’re putting a system in place to establish trust between users. This is important whenever they wouldn’t be able to establish trust themselves. In some cases, your users might already have a unified interests in cooperating with each other. They might already trust each other to only share accurate information on the database. It could be an application where trust isn’t even a priority. In any of these cases, a blockchain might not add much value, but in a case where trust is a priority and the users can’t trust one another, a blockchain is a great solution. If this is the case, you can answer yes to this question. Next, can your application operate without a trusted third party? If you’re using a blockchain, you’re attempting to replace the trusted third party. In a case where you’d still be depending on them to operate, you might consider not using a blockchain. If you can operate without becoming the trusted third party, you can answer yes to this question. Finally, can you operate without having control over permissions of the data? When using a blockchain, you won’t have the ability to strictly control permissions over what the users can access, all data will be shared and owned by the network. For example, if you wanted to make a social media application, but also wanted to monitor user behavior and block users that you don’t approve of, then a blockchain might not be the best choice. If your application can work without having control over permissions, you can answer yes to this question. At this point, if you’ve answered yes to each of these questions, then a blockchain could be an excellent choice for your application. If not, try to consider why you’ve answered no to some of these questions. Is there a way to tweak the functionality of the idea to become something that is better suited as a blockchain application? You don’t want to force using a blockchain where it isn’t needed. Traditional databases are more than capable for many situations. But it is worth thinking through some of these ideas, to figure out if maybe you’d want to approach your application a bit differently than you had imagined. This will ensure you have the best opportunity to build a successful blockchain application.

05. Choose A Type Of Blockchain-EoNSchlDiGc.en

Knowing the basics of how each type of blockchain works, we can now decide which of these is the right one for our application. We can do this by asking ourselves questions. First, will all transactions be public? In this case, everyone will have full access to the data in the network. If that works for your application, you can choose a public blockchain. In most situations where a public blockchain won’t work, it’s because there are some regulations or permissions that a company will need control over. When working with company data, that’s particularly a good time to think of the next question. Will all transactions be restricted to only specific users? If the answer is yes, then a private blockchain is probably the best option here. Another note though, is that it’s also a good time to consider if you need a blockchain at all. Like we mentioned, a lot of the value of a blockchain is thought to be its open access. It’s possible that a private blockchain is the right solution, but be sure to consider the value a blockchain is adding if this core benefit is being restricted. Finally, ask yourself this. Should some information be public, while other information is restricted? This could be the case if you want to share information across multiple companies, but not have it be completely open to the public. If the answer is yes, then a hybrid blockchain could be the right solution in this case. These questions are a great starting point as a check for any new ideas you might have. To make the final decision, we’ll take some extra thought as you consider the unique situation you’re up against. Once you decide which type of blockchain you’d like to use, there are still many things to consider about how to implement it. To understand how it could be implemented, it helps to dig in and see what the underlying data structures could look like. We’ll cover that next by exploring data in the Bitcoin blockchain.

05. Types Of Blockchains-SOAk2DKowyQ.en

Once you decide that a blockchain seems like the right solution, you’ll need to think through which type of blockchain you might want to use. There are three main types of blockchains. A public blockchain, a private blockchain and a Hybrid Blockchain. In this video, we’ll define each of these blockchain types and cover when each might be the best solution for your application. First, a public blockchain is what we’ve been assuming through this program so far. On a public blockchain, everything is open for the entire network. Anyone can join and get access to add and verify transactions. Bitcoin is an example of a public blockchain. A private blockchain is basically the opposite of a public blockchain. You get the functionality of a blockchain, but still have the ability to restrict who can join the network. Rather than anyone being able to join and verify on the network, you can explicitly assign those permissions to specific users. This is similar to the difference between an internet and an intranet. The Internet is freely available and accessible to anyone, but companies may use an intranet to share secure internal documents. This allows them to keep permission restricted to the users within their company. That’s exactly what you can do with a private blockchain. You can restrict users to the people in your company or to any group you have in mind. Private blockchains have an interesting reputation. Some people say they’re useless and defeat the whole purpose of the blockchain. If you want full control over information you don’t plan on sharing, then why not use a traditional database. On the other hand, some major corporations seem to be pushing the idea of privately hosted blockchain services. One useful possibility of a private blockchain is to restrict access to features that are still being tested. You wouldn’t always want full open access to features that you’re still working on and testing before deployment. A Hybrid Blockchain is a mix of both a public and private blockchain. In a hybrid Blockchain, transactions stay private while allowing a network of users to create and validate transactions. Owners of the blockchain, can determine which transactions should only be visible to certain smaller groups and which can remain public. The goal here is to get the best of both worlds. For example, you might be a company that wants to share product information with other companies and allow a subset of that information to be available publicly. As a food distributor maybe you track the price and ownership of your products supply chain as they move from the farmer to the consumer. You can track this on any blockchain, but on a Hybrid Blockchain you could set certain restrictions. You can share all the information with the companies that are involved but if you want consumers could be restricted from seeing the price at each stage in the supply chain. This would allow them to see that the food is really coming from where you say it is but wouldn’t show them some of them were classified information that you’d prefer to hide. While it’s easier to think about use cases for a Hybrid Blockchain, it’s similar to a private blockchain and that some people really don’t like the idea. It’s easy to see that this is a form of re-centralizing the information to be restricted on an as needed basis by the company in control of it. What you do get from this though, is a middle ground where information can be shared on the blockchain even if some of the information needs to be kept through yourself. So to recap, we just went over three types of blockchains. Public, private and hybrid. Each of these networks operates using the same encrypted data using wallets and keys like we’ve spoken about previously. Where they differ is in how much you have the ability to restrict access to this data. public blockchains allow open access to all the data in the network and allow anyone to become a node in that network. Private blockchains do the complete opposite and restrict this data to only specific users and finally, Hybrid Blockchains are a mixture of these two types that allow you to restrict some information while allowing other information to remain public

06. Choosing A Blockchain Motivation-qCS5YuqbymA.en

So, we just got done learning about different types of block chains, like public, private, and hybrid. And we’re about to jump into the data model that kind of underlies any of those block chains. And I was wondering if you could explain kind of why that’s important to understand? It’s super important. When you sit there and think about the different types of block chains that exist, we have private, public, and of course hybrid. And it was fantastic, we just got done learning those differences. But, now it’s time to explore block chain data model. We want to understand what that data really is and how we can work with it. That’s going to dictate the type of usage in regards to a block chain type. Sometimes, data should be exposed on the private chain that’s not accessible to the public. That’s a great use case for having a private block chain. There’s of course, so many more ways to go ahead and experiment with this, but the very first thing that we know, we need to explore. So, let’s go ahead and start exploring block chain data. Great thanks Brandy

07. P2P Network Vs ClientServer Model-cdknEf0y250.en

As we’ve seen, the blockchain works using a peer-to-peer network. It’s useful to understand how this compares to other possibilities. Is it better, worse, or just different? Well, it’s actually more about picking the right tool for the application than trying to decide if one is always better than the other. Here we’ll start by defining another type of network, the client server model. From there, we’ll be prepared to compare them to decide when each might be a better fit for your application. Let’s walk through the details. A client-server model is an application structure that breaks up tasks between service providers and service requesters. A server is a centralized resource that contains the information that users want to access. The client makes a request to the server and the server responds with the information the client needs. There are different types of servers depending on the situation. Web servers serve websites and file servers serve computer files. You can even take the client server analogy beyond computers. Anything that provides any service like food or beverages is a server and anyone they serve is the client. A client server infrastructure can contain many separate servers, but these servers are owned by a single authority. For example, Google, Amazon, Twitter, and many other sites keep their data stored across servers that they own. Having many servers helps ensure that if something happens to one, then information isn’t lost. Clients or users like us will go to a website. Any action we take like asking a question or searching for a product is a new request to the server. Once the server finds the information you’re requesting, it will serve it to you and load it onto your web browser. A single server can serve requests for many clients. They do this using a communication protocol that is built into the network. This request and response drives the entire relationship between clients and servers. This client server relationship is similar to the P2P network but the way it’s executed is different. A peer-to-peer network is a network of computers that share access to files with each other. In peer-to-peer networks, every node is both the server and the client. They both hold information that others can access and can request information from others. The peer-to-peer model allows us to have distributed or decentralized networks rather than centralized networks like in a client-server model. There’s one important thing to know as a potential problem of peer-to-peer networks in the case of Bitcoin and other proof-of-work blockchains. If you have access to more computing power, you can allocate more resources to mining and get more rewards for your effort. This gives you more money to buy more computers and get even more rewards. This cycle has caused problems for peer-to-peer networks using proof-of-work. The larger miners keep buying more resources, getting larger and larger and this centralizes all the work happening to just a few nodes. Centralizing the power and information defeats the purpose of a distributed network and is a major reason why the blockchain is turning to solutions outside of proof-of-work. Coming up, we’ll look at some more differences between these two models.

07. P2P Vs Client Server Features-n3H-hrI9jT0.en

Previously, we defined the client server model and began reviewing some of the differences between this and peer to peer networks. In this video, we’ll explore the differences between these networks in more depth. We’ll look at how they operate using five different categories; infrastructure, cost, control, security, and stability. This will help you better understand when you should use a certain type of network, why it’s best suited for a given circumstance, and how to apply it to your application. To start, let’s look at the infrastructure of each. As we saw previously, the client-server model is generally a centralized model. While it’s network may contain many servers, they’re usually owned by a single corporation. This is different than a peer-to-peer. Here, the network is distributed across all the users in the network. Each of these users, known as nodes, are responsible for acting as both the clients and the servers. Next, let’s look at the cost of each of these models. The client server model is more expensive upfront than a peer-to-peer. To make it client-server model work, you need to have a significant enough amount of availability to serve all the requests you’re receiving. It’s on you to make sure they’re accounting for all of this and have the appropriate resources needed to keep things up and running. There are options available to make using the service cheaper, such as cloud service providers that allow you to access their server space. This is an alternative route that you can use for an application, but we’re only really considering the cost here as the cost of setting up those original servers that you’d be borrowing space from. With a peer-to-peer, the load is distributed across all the nodes that join the network. You can join a peer-to-peer right now using your local computer. The cost of all the local computers being used to support the network can definitely add up to be very expensive, but in this case, both the load and the cost of the network is being distributed across each of the nodes. Next, when looking at the control of data, it’s pretty simple to see the difference and we’ve covered this a few times already. In a client-server network, the central authority that serving the information has the authority to do whatever they like with it. If YouTube doesn’t want a video shown, they can delete it. If Twitter thinks the user isn’t following their guidelines, they can block them. In a peer-to-peer network, no one has the ability to do either of these things. Everything on the network is owned and shared by everyone. You can choose to leave the network, if you like, but you can’t be blocked deleted or removed by a central authority. Next up is security. How does this differ between the two types of networks? Information security is a huge topic but for this comparison, we’re focusing specifically on security as it relates to how easily someone can access the information on a network. Since the client-server model is run by a central authority with the ability to control permissions across the network, it’s generally considered to be much more secure. In the peer-to-peer networks, nodes are free to share data across the network and any user will have access to this data. As we’ve seen on the blockchain, this can vary between public, private, and hybrid blockchains. It’s important to note that just because peer to peer isn’t as secure as the client server model, that doesn’t mean that the blockchain isn’t secure. That’s because the peer-to-peer itself isn’t what’s contributing to the security of the blockchain. The blockchain security comes from using private keys, public keys, wallet addresses, and cryptography, like we’ve seen before. These security measures have all been added in to compensate for the fact that a peer-to-peer alone doesn’t guarantee security, it just distributes the control. Finally, the stability of the network varies across these network types. Overall, a client-server model is generally considered more stable. That’s because the central owner can add or remove computation and storage more easily to meet the demands of the clients. A peer-to-peer network is generally less stable, especially when it’s getting started. By depending on users to serve up information, you’re placing your stability in their hands. If there are only five peers in the network and three of them leave or the computers break, you just lost 60 percent of your network’s power. Instability goes down as more nodes are added to the network. If your network now has 1,000 nodes, those same three nodes could crash but it wouldn’t have as much impact. That wraps up our overview of the peer-to-peer versus client-server model. The goal here isn’t to decide which is better overall, but to understand the pros and cons of each to determine which is a good fit for your application. The application you build in this program, we’ll use a peer-to-peer model. Take some time to consider what decisions you can make to best leverage the strengths of this model and ways you can avoid some of the pitfalls with this technology.

08. Explore Bitcoin Data Part 2-aNSwRWpd8L0.en

We just saw how to investigate blockchain data, using an online block explorer. We’re not ready yet to explore the data programmatically, like we mentioned. For that, you’ll need to download some software which will focus on in a later lesson. For now, we didn’t want to prepare you for what you can expect to see when you start exploring this data. For this example, we’re using the same data we saw with the block explorer. This is considered to be human readable format for this data. It’s structured using Json into a set of key value pairs. Here we can see all the same data that we did before. Here’s the block header, which contains the hash, confirmations, and many other details. As we mentioned, when using the block explorer, the most notable is the block hash, height, previous block, and timestamp. You might not know what all these are yet, and that’s fine. If you’re curious, you can go to the Bitcoin developer glossary to learn more. We put a link to this down below the video. Here, we can also see the body of the block which contains the hash of each transaction held in the block. Using the hash values, we can investigate the details of these transactions. Let’s take a look at this blocks coin-based transaction. Coin-based transactions are easy to find since they’re the first transaction in the block. What we see here, looks a lot like the block header, but now it’s the information for this specific block. The most important information, is the transaction id, hash, transaction inputs and transaction outputs. This might look a little different than before, but it’s still the exact details we had seen about our transaction when we used the block explorer. Here’s the transaction inputs and outputs just like before. First, we’ll look at the transaction inputs shown here as VIN. When Bitcoin is sent, inputs are collected from the network and combined together to send to the address specified by the sender. The amounts that are used as the inputs are what is shown here. These inputs are combined together to make up the amount sent, the minor fee, and any change that is due back to the sender. Let’s look at each of these in the data we have here. The transaction outputs are shown here as VOUT. First, they show the amount sent and second, the change that was given back to the sender. In this example, we can see that over 12 Bitcoin were sent and that no change was given back to the sender. The change is the value of the full input minus the value sent minus the miners reward. In this case, there’s no value left over so there’s no change to be given back to the sender. That’s the basics of this data using the human readable Json format you’ll encounter later in the program. One last thing we wanted to cover is what it looks like for a transaction to be in non-human readable format. Hopefully that clears out why we keep using this term. Let’s take a look at a transaction. Transactions in the network needs to follow the Blockchain protocol. In this case, the data needs to be formatted in a hex encoded string. Hex encoded is just a specific format that uses characters ranging from zero zero to ff. As you can tell, it’s not friendly to look at. We’ll encounter these sometimes and it’s important to know about them but it doesn’t ever get any easier to read. That’s everything we wanted to cover about block and transaction data for now. Take some time to look at data in the block explorer, then come back and see how that’s represented in this new data format. It helps to be clear how each of these basic ideas are represented. Whether it be on a website, a data structure or later on in an application.

08. Explore Bitcoin Data—Z4BfhfbTkQ.en

Previously, we covered some of the questions you can ask to decide if a blockchain is the right solution for your application. Once deciding to use a blockchain, it’s important to know how the data is constructed so that you can use it effectively. In this video, we’ll explore some of this data and investigate the structure of a block. Blocks contain two main sections that each hold important data. The first section is the block header. The block header contains metadata about the block including things like the hash value which allows to connect blocks into a chain. The second section is the body of the block. The body contains all of the blocks transaction information. We can investigate this data using a few different tools. To start, we’ll take a closer look at this data using an online block explorer. Later on, we’ll be doing this type of stuff programmatically. We’re starting with this website so you can focus on the contents of the block rather than worrying about getting set up with your programming environment. If you’d like to follow along, you can go to the website block explorer.com or follow the link we’ve provided in the notes below. All right, let’s get started. Let’s begin by going to a specific block. You can do that by typing a block number over here in the top left. For this example, I’ll use block 520607. But feel free to use whichever block you like. After Choosing a block, you’ll see the block header. There’s information here like the hash, height, timestamp in previous block. If you click on the previous or next block, the site will load information for whatever details are included for that block. Now, let’s take a look at the block transaction data. You can scroll down to the bottom of the page to see each of the blocks transactions. This information makes up the bulk of the blocks data. They’re listed in order as they were verified on the network. At the top is the first transaction and way down at the bottom is the most recent transaction. This first transaction is known as the coinbase. There’s not really anything special about it, it’s just the term used for the first transaction. Scrolling through to see some other transactions, you’ll notice that each of them contains certain details. On the left is the transaction inputs and over on the right is the transaction outputs. Down at the bottom is the fee, the number of conformations, and the amounts sent. Let’s look at this transaction. After clicking on the hash value, you’ll see some of the summary data about the transaction followed by the details of the transaction inputs and outputs. These are the same details that were provided on the main page. This is telling us that these two inputs were added together giving us these outputs. The top one is how much we sent and the bottom one is how much change was given back to the sender. You can also see that to make this transaction, the miner collected this much as a fee. There are this many confirmations and this was the original amount of Bitcoin that was sent. That’s the basics of how to get started with this online block explorer. Using this, you can continue to explore block data and transactions. This will help you get more familiar with how the ideas behind how a block works actually translates into real-world data

10. Explore Bitcoin’s Codebase-eY1u84y4eC4.en

The cool thing about bitcoin and the mining process is that it’s not hidden from us. The codebase is public, and we can look at it for ourselves. This helps us better understand the process behind how certain things happen and how we might be able to improve the mining process by improving the code. In this video, we’ll explore a few variables that help support bitcoin mining. We’ll look at the code that makes the genesis block, the original timestamp on that block and a few other variables. It can be a bit overwhelming to jump into an entire repository. Here, we’ll just focus on a few key points and from there, hopefully, you’ll be comfortable enough to explore a few more on your own. If you’d like to follow along, there’s a link to the bitcoin codebase down below the video. So, let’s get started. To start, navigate to the source folder, named here as src. In this folder, you’ll see a number of important files and folders. One of these is chainparams.cpp. This is used to set up the consensus rules for all the blocks. This is exactly what we’re interested in. Click on this file to open it. One thing to note is that this file has a.cpp extension. That tells us that this is a C++ source file. You might not be familiar with C++ but the naming convention is just like how.js tells us that something’s a JavaScript file. So, let’s look at the code. The first thing we see here on line 17 is a function to create a genesis block. Notice the variables for that time of creation, the bits, the nonce, the version, and some other information. Being familiar with some of these ideas, it’s pretty cool to me to see how they’re actually implemented in the code. Next, I’ll hit down the line 94. Here’s where the different deployments of bitcoin improvement protocols are set up. For example, there was an update to the codebase known as CSV. You can see here that the changes were implemented at this time and that it’ll stop at this time. Just a bit above this line, we can also see some variables used in consensus. Let’s look at a few of them now. Here’s one on line 77, nSubsidyHalvingInterval. This is what designates the halving interval. You might not be familiar with the halving interval, but hopefully you remember that miners are rewarded with bitcoin. Halving is the idea that after a certain amount of blocks are mined, the reward for all miners is cut in half. It’s sad, but true. It’s one reason why mining is not as profitable as it used to be. This line shows us that the halving interval is 210,000. This means that the amount miners are rewarded for successfully mining a block is halved after every 210,000 blocks. Here’s a chart to show a little about how the having has happened over time. Until block 210,000, miners earned 50 bitcoin for each block they mined. From then until block 420,000, they earned half of that, 25 bitcoin. This trend continued and will continue for every 210,000 blocks. The fee they earn is on top of the transaction fees that they collect. These bitcoin are actually brand new coins that are added to the collection of all bitcoins. It’s the only way new bitcoin are created, and this process helps control the supply of bitcoins available. All right, so let’s get back into the code. There’s two more consensus constants that I wanted to call out. They are in line 84 and 85, nPowTargetTimespan and nPowTargetSpacing. First, nPowTargetTimespan sets how often the proof-of-work puzzle adjusts its difficulty level. Here, it’s set to every two weeks. nPowTargetSpacing determines when the network should expect a new block. Here it’s set to every 10 minutes. This 10 minutes times 60 is just to convert the time to seconds. So, that wraps up some of the lines we wanted to look at in the bitcoin codebase. To recap, we looked at the genesis block, its original timestamp, and a few consensus variables, like those related to halving as well as the proof-of-work timespan and spacing. You can hopefully explore a few more lines on your own. It can maybe discover how certain things you’re interested in have been implemented and the bitcoin blockchain. A lot of these same ideas have been used on other blockchains and it’s important to see how they’ve gone about doing this. Coming up, you’ll have a look at another codebase to see how some of these ideas have been implemented there.

11. Bitcoin Improvement Proposals-ND_kTosMjf8.en

The Bitcoin protocol is made up of a bunch of rules. Sometimes, a rule of the Bitcoin protocol needs to be changed. For example, how should miners be rewarded? How large should a block be? Decisions have been made on this already but that doesn’t mean they can’t be improved. These are the types of questions that can affect how the entire network operates. Bitcoin, like any software project, is always improving. So updates like these will continue to happen as the software evolves. In Bitcoin, this process of updating the software starts with a Bitcoin Improvement Proposal. Bitcoin Improvement Proposals are technical documents used to issue changes to the Bitcoin Core Client. We discussed this earlier in the program when we went over BIP 39, which helped create deterministic wallets. You can find this and other Bitcoin Improvement Proposals at github.com/bitcoin/bips which we’ve linked below the video. These proposals are written by community members who believe they can improve the protocol. They’re sent out to the network and published publicly. At this point, the proposal is only a suggestion for an improvement. Before being implemented, the proposal needs to go through a voting process. This vote is taken by the miners in the Bitcoin network. If the proposal gets a majority vote from the miners, it’ll be implemented. This means the miners actually have control over the implementation of updates to the network. Miners are a good choice for this because they’re clearly invested in the improvement of the protocol. Once a vote is taken, the proposal is either accepted or denied. If accepted, it’s time to start implementing the proposed changes into the software. This works and continues to drive improvements to the Bitcoin protocol but there are some concerns. For one, miners are important but they don’t always represent the best interests of the entire network. This can be a problem. For example, miners can vote for proposals that favor themselves and turn down proposals that may hurt them. If something could improve the network performance but lower miner fees, it may get denied because the miners are concerned about the money they can earn. It could be that this is the right move but it is a situation where miners have to choose between personal incentives and progress. The system works pretty well but, we want to point this out because it is somewhat of a concern for the network at this point. Depending on how significant a change is to the network, it can be really difficult to get everyone to agree on the right direction. It’s possible for some users to adopt the change and for others to deny it. If this happens, the network splits into those who have adopted it and those who haven’t. These network splits are known as forks. Coming up, we’ll discuss the different types of forks that can happen.

11. Hardforks-rj3kyOXzqIk.en

One type of update that can happen to a Blockchain results in what’s known as a Hard Fork. In this video, we’ll go over what a Hard Fork is, what effects it can have on a network, and look at an example using Bitcoin cash. A Hard Fork is a large change on the blockchain protocol. It’s a permanent change to the software that conflicts with the existing version resulting in an entirely new software. Once a Hard Fork is implemented, it creates an entirely separate network. Users will need to choose if they want to stick with the current network or choose the new one. This happens because of how the change occurs. In a Hard Fork, software developers create an exact copy of the entire Blockchain protocol. They can do this because the codebase for most block chains are completely open source. Once the developers make this copy, they write their new code into the software. Next, they need to decide when this change will take place. The way they do this is by specifying a block number. For example, you could say, “Once we reach block 100 our changes will be implemented.” At this point, some nodes continue with the original version and others transition to the alternative version. They show their support of the version they chose by adding blocks only to this new chain. Since each block chain is now building a different history, they’re no longer compatible. Even though they’re now operating separately, they still have a shared history from before the fork. That means that all transactions that happened before the fork are valid on both chains. This results in something pretty interesting. Since you have a history of valid transactions, they need to be represented on both chains. To make this happen, the coins you had on the original version are duplicated and given to you on the new version. So, if you had 100 coins on the original version before a Hard Fork, you’ll also have a 100 coins and whatever currency was created by the fork. These coins are entirely separate from the original coin and their values don’t affect each other at all. Some people call this free money, but that’s only the case if the new currency ever gets accepted enough to gain any real value. Hard Forks have happened on many different block chains already. As an example, you may have heard of Bitcoin cash. This currency was originally created because of a disagreement on the block size of a Bitcoin block. Some developers wanted to double the current block size and others wanted to make it even larger. When they couldn’t come to an agreement, some developers went with an increased size and other stayed with the current block size. That’s why we now have bitcoin and Bitcoin cash. To recap, a Hard Fork is a major change to the protocol of a Blockchain. It creates an entirely alternative software that is incompatible with the original. This is different than a few other types of forks that we’ll discuss next.

11. Softforks-cSl557aVv4U.en

Hard forks and soft forks are pretty similar overall, but the end result is much different. In this video, we’ll go over what a soft fork is and how it’s different from a hard fork. Then we’ll go over an example of a soft fork known as segregated witness. A soft fork is a small change to the software protocol. This change makes it said that the updated version is still compatible with the original software. The changes made to the software are compatible with the original version. This differs from a hard fork where the changes are not compatible. In a soft fork, there’s no permanent split in the chain. There may be a temporary split, but that’s only to allow time for the changes to propagate through the network. Once everyone has upgraded to the updated protocol, the updated version of the network will be the only one that exists. An example of a soft fork is an improvement known as Segwit. Segwit, short for Segregated Witness, was a soft fork of Bitcoin meant to increase the amount of space available in each block. It allows a block to hold more transactions by removing the signature data from each transaction. Without this signature data, each transaction takes up less space which allows more of them to fit in each block, that’s why it’s called segregated witness. It’s separating or segregating the witness which is the signature data from the transaction. We can use this as a great example to see the side effects of an update once it gets implemented. For one, if your wallet doesn’t implement Segwit, you’ll still receive transactions from wallets that do. What you end up with is transactions that you can’t validate. This is why in a soft fork, you’re required to update to the latest version of the protocol. Also, this update like all soft forks, is a trade off between both the advantages and disadvantages of implementing it. Segwit was able to improve the block chains efficiency, but also open the door for possible new ways to attack the network. In this case, Bitcoin decided that the benefits of improving the network outweighed the potential downsides. So, Segwit was implemented as a soft fork. To recap, a soft fork differs from a hard fork in a few ways; rather than being a large update that is not compatible with the original software, it’s a small update that is considered backwards compatible.

11. Source Code Forks-FCj9EFBt68c.en

We previously discussed hardforks and softforks. It’s important to note that there’s also something called a source code fork, which is neither of these. A source code fork is the term used for copying the entire codebase of an existing project to a new project. We mentioned that a source code fork happens in both a hardfork and a softfork because there needs to be a copy of the code base made. But, it’s possible to create that copy then never tie back the updated software to the history of the software’s blockchain. To be a softfork or hardfork, there needs to be that connection to the original blockchain that the new software was forked from. In a hardfork, the network maintains a shared history of transactions and in a softfork, they maintain both their history and future transactions. An example of a source code fork is light coin. Light coin is a source code fork of Bitcoin that resulted in an alternative currency. With light coin, they copied the Bitcoin code base, implemented their changes, and created an entirely new block chain with no association to Bitcoin. The currency now trades as a completely separate alternative to Bitcoin. To recap, changes are implemented in Bitcoin using the Bitcoin improvement proposals. These changes are voted on by minors and implemented by software developers. These changes result in either a hardfork or softfork. In a hard fork the new version is permanent and completely incompatible with the previous version. In softfork, the network only temporarily splits as the change rolls out. Both of these are different than a source code fork, which is just a copy of the existing code base with changes that break any relationship to the existing chain. In the following quiz, try to see if you can identify the different examples as either softforks, hardforks or source code forks.

13. End Of Lesson Motivation-bucxEn2ovYU.en

All right. So we just went over a few things like hard forks, and soft forks, and I know a question I had when I first got started was, is there a way for me to get involved like what community is really making these changes and where do I even go to do that to get started? So I was wondering, do you have any idea about how someone might be able to get involved with the community that could help make these types of changes we’re talking about. That’s a great question. You know, with all great things open source, there’s a community that’s driving those projects and the go-to right now is GitHub. And like, I think we all understand the power of GitHub, right? You have a GitHub account, I have a GitHub account, I’m assuming you have a GitHub account as well. So what you can do is start participating in the community, it’s very active and rich. We’ve seen a lot of politics come across in the blockchain space, like with the recent hard forks that came from Bitcoin, Bitcoin versus Bitcoin Cash. It’s really interesting the political debate that goes on and the biggest difference was block sizes, right? Like that was a big driver between the original Bitcoin and Bitcoin Cash, but it’s interesting because those politics allow all of us to participate. We get to go ahead and select which ones that we have most alignment with and we can go ahead and embed ourself within those communities. I would definitely advocate to start being active in the community within GitHub, and if you have an improvement that you would like to propose, go ahead and submit a pull request with the improvement and who knows, it might get adopted within the platform. Great. Thanks Brandy.

14. Lesson Summary-bA0GQG11v0s.en

All right. We’ve reached the end of this lesson. Congratulations. Throughout this lesson, we covered a ton of new material on the blockchain as a dataset. We walked through some of the basic ideas, like when to use a blockchain? And how it compares to other possibilities? From there, you explored blockchain data using the Blockchain Explorer. Finally, we covered a few core ideas like peer-to-peer versus the client server model. How the mining process controls the chain and softforks versus hardforks. We’ll continue building on these ideas in the next lesson, where we start working with the Bitcoin Core Client. We put a quick overview of this lesson down below the video. Check this out for a few more details, and when you’re ready, we’ll see you in the next lesson.

img

Part 03-Module 01-Lesson 02_Bitcoin Core Testnet

01. Lesson Introduction-bmt_QHOfZCM.en

Welcome to the lesson on Bitcoin Core. Bitcoin Core is a powerful set of developer tools to help you create applications on the Bitcoin blockchain. The goal of this lesson is to get you up and running with your own Bitcoin Core development environment. Throughout this lesson, we’ll introduce Bitcoin Core, its purpose, and the tools it makes available to you to help build and deploy applications. Once set up, you’ll start to create transactions between wallets using a Bitcoin Core test environment. You will investigate the transactions made using the online Block Explorer to get better idea of how transactions flow through the network. All this, will prepare you to complete your next project, where you’ll start to make transactions using your own private blockchain. For more details on the upcoming lesson, feel free to read through the text below the video, and when you’re ready, we’ll see you in the lesson.

02. Bitcoin Core Motivation-notH8-LKL2o.en

Hey guys, and welcome to the lesson on Bitcoin core. So with that, I want to ask you, why did we choose Bitcoin core for this lesson? So, honestly the motivation was the fact that Bitcoin core literally was the original Bitcoin. So, Bitcoin, when Satoshi Nakamoto released it to the community, it went through a lot of trials and tribulations especially when we started doing soft forks and hard forks and we have new forks like Bitcoin cash, which almost adds confusion to the adoption of this technology. So, the original community decided to go with Bitcoin core because it is the core bitcoin that literally started it all. And so we wanted to go ahead and establish the fundamentals right from the source. Right? And that’s why we selected Bitcoin core. That makes sense. So going back to where it all started, there was a lot of work that’s been done on it through the years. With that in mind, what excites you about Bitcoin core? Number one excitement is the fact that it was the original, right. I like the idea that we can take something that was so new and improve it over time. And so, honestly, by admiring Bitcoin Core, it allows me to respect the motivations the fork with Bitcoin cash and the new technologies that we’re seeing float today within the blockchain space. And so to me it reminds me of the fundamentals. That’s another reason why I absolutely love Bitcoin core. It’s because it just establishes those fundamentals for me and I believe for everybody in the community. Yeah. We can see a lot of the basics actually all go back to it and so we can really experience it there. So do have any advice for students as they’re starting off this lesson? Yes. So the tooling is extremely important. And as we noticed, there’s so many different platforms. So some of the things that we’re going to do with Bitcoin core is really focus on what type of tooling is there and that tooling should allow an introduction to other platforms. We want to try keeping it as universal as possible. So, the message that we’re going to learn within our program is absolutely adaptable no matter what platform you decide to choose within the blockchain space. Yeah. I think that’s a great perspective to have as they’re beginning this lesson. Well, so with that, let’s get started

03. Bitcoin Core Overview -LmGEpGwhEU0.en

The term bitcoin is used a lot. But it’s a little unclear sometimes what it means. It’s mostly known as a cryptocurrency, but there’s a lot more to it than that. It is generally an umbrella term used to describe everything about bitcoin. But aside from the currency, there are actually two very distinct functions of bitcoin to understand, and in this video, we’ll explore these two functions. Bitcoin as a network, and bitcoin as a software. We’ll help clear up some of the confusion, and discuss how each of these two, work together. So, the term bitcoin specifically refers to the network of bitcoin users creating and validating transactions. Aside from this network, there’s a software behind the bitcoin that makes it all work, and this, is known as Bitcoin Core. Bitcoin Core, is an implementation of bitcoin that encompasses all the software behind bitcoin, that allows the network to function. This is where all the developer tools environments exist. Initially, this software was published under the name bitcoin. But as the network grew, it became more important to make a distinction between the network, and the software. So, the software was renamed to Bitcoin Core, to clear this confusion. Through its history, it’s been called Bitcoin-QT and it’s sometimes referred to as the Satoshi client. So if you see these names anywhere, Keep in mind that these refer to same thing. Previously in this program, we focused on Bitcoin as a network. But throughout this lesson, we’ll transition to Bitcoin Core, and start to explore the tools available to you as a Bitcoin developer. There are a few essential features of Bitcoin Core, that we’ll discuss. First, the Bitcoin Core transaction verification engine. This connects the Bitcoin network as a full node allowing you to verify transactions happening in the Bitcoin network. Another feature of Bitcoin Core, is the ability to explore and validate the entire Bitcoin blockchain, which is a history of all those Bitcoin transactions that have taken place. Finally, it provides a cryptocurrency wallet, that allows you to transfer Bitcoins. As a developer, you’ll interact with these features using the command line interface in the Bitcoin Core debug console. The debug console, is a powerful tool that allows you to interact with data on the bitcoin blockchain. And after getting up to speed with your own environments, you’ll spend a lot of time exploring data in this tool. As a developer, you also get access to other networks, where you can test bitcoin applications in an environment that mimics the features of a live network. And understanding these features, will allow you to get set up, and start running as a Bitcoin Core developer. We’ll learn all about these features, and how to implement them, throughout the rest of this lesson.

04. Bitcoin Core Networks-eHroZsYBPwY.en

An important part of the Bitcoin core ecosystem is the different networks that are provided for you. These environments are for developers to test and deploy Bitcoin applications. To do this effectively, they provide three different networks each serving a different purpose. These networks are the Mainnet, the Testnet, and the Regnet. In this video we’ll explore the purpose of each of these networks to help you understand when it’s best to use them. The Bitcoin Mainnet is the one you may already be familiar with just not by the name. It’s a primary network where live transactions take place. Everything you have heard about sending Bitcoins and using wallets is all taking place on this network. The coins used here have real-world value and is what you’ve been accessing using your Bitcoin wallet. The purpose of this mainnet is to handle live transactions with coins that have real-world value across your network appears. This is great for providing all the functionality of Bitcoin, but it makes it difficult to test new applications on it without slowing down the network. To handle this, Bitcoin core has a test environment meant for testing applications. The Bitcoin Testnet is an alternative Bitcoin blockchain to provide a test environment for Bitcoin applications. In the Testnet you have access to Testnet coins. These coins have no real-world value and allow you to test the functionality of your application without needing to spend real Bitcoins. The goal is to allow you to develop a personal sendbox environment without having to spend real bitcoins and breaking the Mainnet. This allows you to interact with peers on the network that is entirely separate from the Mainnet. One key function to note is that it still operates as a network. Things like creating new blocks and validating transactions still have to be done using the network. This can slow down testing time if you wait for a block or transactions to complete their life cycle. To help address some of these concerns and speed up testing, the Regnet was created. The Regnet, short for regression test mode is an alternative network for testing Bitcoin applications. Like the Testnet, you’ll use this network for testing applications using coins that have no real-world value. The difference is that on the Regnet, you no longer have a network appears to work with. You can instantaneously create new blocks and have complete control over the environment that you’re testing in and this will significantly speed up test development time. Each of these networks has their own specific use cases and gives you the opportunity to create, test, and deploy new Bitcoin applications as efficiently as possible. Coming up, we’ll compare each of these networks and a little more detail then get you up and running with them.

05. Mainnet Vs Testnet-U2BaioVC9Ys.en

Now that we have a basic overview of the value of each Bitcoin core network, we can dive a little further into the details of each. This helps you so you’ll know not only why each network was built, but some of the specific functionality behind why you might choose one over the other. In this video, we’ll focus specifically on comparing the mainnet to the testnet. We’ll walk you through each item listed here on the left to help you get a better idea of how they compare to one another. To start, remember that the Bitcoin mainnet is the primary network where live transaction take place. This live network isn’t the ideal place though to build and test applications. To do this, the testnet was created. The testnet is an alternative Bitcoin blockchain that provides a test environment for applications. This helps reduce risks and limitations associated with Bitcoin core. Now, how do they compare? First, we know that the mainnet is for deploying live applications for production, while the testnet is only used for testing purposes. Next, both of these networks are public environments, that means that when you’re using them you’ll interact with a network of peers that create and validate information on the blockchain. But there’s a difference in who makes up the peers in the network. While anyone can join either or both networks, they’re entirely separate from one another. They are different chains with different peers and joining one doesn’t mean you’re part of the other. This has an effect on the size of each network. The Bitcoin mainnet is much larger with more peers and more blocks. To download the full mainnet would take over 200 gigabytes of space right now, while the testnet is closer to around 15 gigs. These will both continue to grow over time and it’s most likely that the testnet will continue to stay smaller than the mainnet. But there’s no limit to how large either of these can get. Remember, the size will keep growing because all data is held forever on the chain and more blocks are added as more transactions take place. The time to create a block is similar on both networks. In each case, it takes approximately 10 minutes to create a block and that’s because in both cases blocks are both created and validated by nodes within the network. That means that it still takes time for a transaction to go through each step in the life cycle and this takes about 10 minutes. One major difference between each of these networks is the value of the currency. Bitcoin on their mainnet are worth their full value but testnet coins are not worth anything at all. One quick thing to note here is there have been times that users have tried to collect and sell testnet coins. Since there’s a limited number of coins in the testnet, just like there are limited number in the mainnet, if people collect these coins it makes it more difficult for others to continue testing on that network. Because of this, developers have wiped out the entire collection of coins to start again from scratch to begin redistributing these testnet coins. This has happened twice so far which has brought us to the third generation of testnet. So if you look around and start to see testnet three, that’s what that refers to. Public keys on the testnet have been differentiated from those on the mainnet by starting with the letters m or n. This helps users see whether they are interacting with the testnet key or a mainnet key. Finally, the block difficulty is different between each of these networks. On the main net, the block difficulty self-adjusts as blocks are created to try to maintain a block creation rate of about one block every 10 minutes, on the testnet the same thing is happening. The difference here though is that less computing power is dedicated to maintaining this smaller network. To maintain a block creation rate of around 10 minutes, the block difficulty has been lowered to approximately half of what it is on the mainnet. So, that’s how the mainnet and the testnet compare across these A characteristics. The core difference is that the mainnet is for live production, while the testnet is for application, creation and testing. The rest of the differences stem from this core idea, to help facilitate the networks used cases. Later on, we’ll be spending a lot of time in the testnet to help build and test applications.

06. Testnet Vs Regression Testing-OL97OIAOM2A.en

We just took an in-depth look at the difference between the Mainnet and the Testnet. Throughout this program, we’ll be using the Testnet to build our application. Before fully committing to this network, it’s important to also understand what the Regnet is. We thought it might be helpful to lay out a comparison between these two networks, then justify why we’ve chosen to use the Testnet for application. In this video, we’ll compare the Testnet and the Regnet to get a better understanding of what the differences are that exists between these two networks. As we know, the Testnet is a development environment meant to allow developers to test their application. An alternative network known as the Regnet is also a local testing environment. The difference is that on the Regnet, developers can almost instantaneously generate blocks on demand for testing. They can create private coins with no real-world value. For our comparison, we’ll run down the list of these eight characteristics. First, for each of these networks, the purpose is for testing applications. Nothing here is connected to the main live network, they’re just tools for development. Even though they’re both retesting, there is a major distinction between these two networks. While the Testnet is a public test environment with transactions that are broadcasted throughout the network, the Regnet is completely private and transactions are only seen on your local computer. This is possible because there are no peers on the Regnet. Transactions do not go through validation and there are no peers whose transactions you’ll interact with. This lack of transactions means that the size is very small in comparison to the Testnet. On the Regnet, you can only download the core components necessary to run the application, and it only grows in size as you create more blocks and transactions yourself. That’s much different than the Testnet where you have to sync to the network and download the blocks. Since there are no peers and there’s no validation, blocks aren’t going through the same transaction lifecycle on the Regnet as they do in other networks. Instead, on the Regnet, you can generate any number of blocks instantaneously, reducing the block time to zero. In both the Testnet and the Regnet, their coins have no value. However on the Regnet, it hasn’t had the same problem with people trying to sell their coins as the Tester has and that’s because even though both are worthless coins, the Regnet coins aren’t even connected to a network that you could try to sell them even if you wanted to. Either way, don’t try to sell either of these coins, they’re just for testing. Another similarity between these networks is that the public keys are preceded with an m or n to differentiate them from the Mainnet. Finally as we mentioned, blocks on the Regnet are created instantaneously. Since there are no nodes and no hashing, there’s also no block difficulty. That wraps it up for some of the differences between these two networks across these characteristics. There are times that you’ll want to use the Testnet and other times where the Regnet is better suited. It’s actually common to hear that the Regnet is a better environment for testing applications. It’s true that it does allow you to do some things much faster than when using the Testnet. But we’ve chosen to move forward with the Testnet for a very specific reason. We’ve chosen the Testnet because we’re doing more than developing on the blockchain. We’re developing a Web service that takes user input to test and verify transactions from users. Since we’ll be testing these applications with the Web service and collecting user information, we’ll need to be able to interact with these users. For that reason, we’re choosing to stick with the Testnet even though it’s a little slower in some cases. Hopefully now you have a better idea of what the Testnet is used for and what the Regnet is used for, and why we are using the Testnet as our testing environment.

08. Bitcoin Core Getting Started-yb82UWqADj0.en

A Bitcoin Core 4 Full Node Wallet is a Bitcoin wallet that fully validates transactions and blocks. By downloading a full node, you’ll be acting as a node that accepts and validates both transactions and blocks from the Bitcoin blockchain. Now being a node is different than being a minor. By downloading this wallet, you’re not participating in block mining, instead you’re only acting as a client that is continuously downloading and validating the blockchain using your local computer. So to download a full node wallet, go to Bitcoin.org, which I’ve linked down below this video. From there, scroll down to the section called “Get Started with Bitcoin.” This takes you to a page where you can select a variety of ways to get started with Bitcoin. Right now, let’s click on “Choose Your Wallet.” From here, you can see a selection of wallets that you can download and we’ll be using Bitcoin Core. From this menu, select the device and operating system that you’ll be using to install the software. For me, I’ll be downloading onto my Mac. Here we have the option to install or to see the source code. In this case, I’d like to install software. Now before downloading, decide the location you’d like to store your wallet. You can store this any where you like, just make sure that you have the space available on your device. Now Bitcoin Core can be quite a large file, over 100 gigabytes, which can easily overwhelm the space that you might have on your computer. Now it is possible to reduce the space taken up either using a technique known as pruning or by syncing to the test net or the reg net. Alternatively, some people would download the wallet to an external hard drive. This allows them to access the data without needing to worry that the space on the computer will fill up as the blockchain continues to grow. Once you’ve installed the wallet, you’ll see that your computer begins syncing to the network. This is your computer taking the time to download the Bitcoin blockchain. So as progress is made, you can see the number of blocks left, when the last block was created, the progress made toward downloading the entire network, and finally how much time is left until you fully sync to the entire version of watching. As I mentioned before, if you just don’t have the space available to download the entire network, you also have the option to either sync to the test network or to the regression network. We cover how to access these networks in a concept titled “Bitcoin Core Networks.” If you’d like, jump to that next for an overview of how to get access to one of these networks. These do come with certain limitations but they’re extremely useful depending on what your goals are. So both of these options are better than having no access to the network. So see if these could be a better fit in a case where you don’t have available space. Finally, while syncing to the network can take some time, the good news is that you don’t need to have all of the data in sync before you start using the wallet. Once you have any information to sync to your computer, you can start exploring it for yourself. Coming up, we’ll explore our new wallet it just a little further.

09. Bitcoin Core Wallet Overview-5_5nFZ0sgkE.en

Once you get your Bitcoin Core Wallet, it helps to takes some time to get used to the basic functionality available to you. And in this video, we’ll overview the basics of this wallet to help get you familiar with this new tool. When you first load up your wallet, you’ll see a note showing how far along your wallet has synced. It shows the number of blocks left along with some other information down by the bottom of the screen. Now this is helpful but I generally hide this right away to get to the more important information. After hiding the first screen, we will be on the overview page of your wallet. This is where you’ll see things like the balance that you have available as well as the recent transactions you’ve made. Along the top here is the navigation bar that you can use to access other parts of your wallet. Let’s click “Send”. From here, we can see the details about sending transactions using your Bitcoin wallet. If you’ve previously used another wallet like Electrum for example, some of this might look familiar. To send a transaction, your Bitcoin wallet requests an address to pay to, a label to help organize the transaction and an amount. You can use these buttons here on the right to copy this information if you need to use it elsewhere. Along the bottom here, you’ll see a transaction fee that you can setup for yourself as well as the ability to send, clear information, and add new recipients through the transaction. Next up, navigate to the received panel. This again hopefully looks pretty similar to other wallets you’ve used. Here, you have the option to request Bitcoin using your wallet. You can enter a label, an amount and a message to the recipient. Once making a request, you’ll also be able to see details like the date and other details of the requests in this window down below. Now let’s navigate to the transaction window. Here, you’ll see the details of all transactions that happened using your wallet. While the overview window gave us a set of recent transaction, this screen gives you a list of every transaction. You can organize these transactions by the date, type, label, and amount similar to ordering a spreadsheet. Along the top, you also have the option to search for specific transactions using any field or by setting constraints to get back any transaction that meets a certain criteria. Now that we’ve seen each window on the main screen, let’s navigate to other parts of the wallet using the file menu. So along the top here you’ll see “Bitcoin Core”, “File”, “Settings” and “Help”. Under “File”, you can sign and verify a message as well as access you’re sending and receiving addresses. Using “Help”, you can access a “Search” bar, the “Debug” window and “Command-line Options” that are available in the tool. The debug console is a tool that we’ll be using to explore blockchain data later throughout the lesson. Now the command line options are really helpful, but they’re for a different use in this case. These allow you to access blockchain data from beyond the debug console using these command-line options. We won’t be going over this in this lesson but it will be helpful later on when we start building applications. Finally, it helps to know where all of this information is coming from. If you haven’t already checked back to the directory where you saved your Bitcoin Core client, try navigating there now. If you’ve saved it to the default location and forgot where it was, check out the link down below. So on the Mac, it’s listed as, saved under library/application support/ Bitcoin. What you’ll see is all the information that is available for your copy of the blockchain. In there you’ll find the blocks, chained state, log, test network, wallet and a few other features. You might not see the bitcoin.conf file like I have here just yet and that’s fine. This is a file that you can use to override some of the standard functionality of the application but we’ll get you set up with your own Bitcoin configuration file soon. Now these are all the basic options available to you when getting started with the Bitcoin Core Wallet. Coming up, we’ll dig a little deeper into this tool and get our hands dirty with the options available to us as developers.

10. Bitcoin Core Network Demonstration-wk2mDncInbA.en

Each of the Bitcoin Core networks, so the mainnet, the testnet, and the regnet can be accessed using the Bitcoin Core client. Switching between each of these environments will allow you to access the features of each network and more easily setup development environments for your Bitcoin application. Even if you don’t plan on switching back and forth between networks, you can use this method I’m going to show you to change the default network of the Bitcoin application. This may be helpful in the case that you don’t want to stick to the mainnet and would prefer to only ever use the testnet or the regnet. Now, in this video, we’ll quickly overview how to switch between each of these networks using the Bitcoin Core client. To start, let’s go into the main network. So, if you actually don’t want to go into the main network, wait for a moment until I start talking about the testnet and then follow along. Now to go to the main network, navigate to your Bitcoin core application and open it up. If you’re opening this application for the first time, or haven’t opened it in a while, you’ll notice the client might take some time to sink to the blockchain. The default network is the mainnet. So, once this application opens, you’ll be on the main network. Next, we’ll switch to the test network. Now there are two ways to kick off the testnet with the Bitcoin Core client. The first option is to run the client with a flag used to set the testnet. The second option, which is preferred, is to use a Bitcoin configuration file. To use the Bitcoin configuration file, you need to create this file inside your Bitcoin core directory. Once created, you can use this file to help provide directions to the Bitcoin Core application. This file will have a few purposes as we move forward. But for now, it helps us get set up specifically to help change networks. To make this file, open up a text editor such as Visual Studio or Sublime, but any simple text editor will do. In this file, type testnet=1. This tells the Bitcoin Core client to load the application into the test network rather than into the main network. Name this file Bitcoin core.conf so C-O-N-F and save this file inside your Bitcoin core directory. All right. That’s all we have to do. So this file is read automatically when you start up Bitcoin core. Since it’s read while starting the program, we’ll need to quit our application and restart it. So, go ahead and restart your application, or if you haven’t opened it just yet you can do that now. What you’ll notice is that while starting up, the logo changes to green and then in top right, you’ll see that it’s marked as testnet. So, these are indicators that you can use to see that you’ve correctly accessed the testnet. Once logged in, you should see that everything looks pretty much the same as before. You have access to a wallet overview and can send and receive transactions. The difference now is that these coins have no value and you can play around in it as a test environment. We’ll spend a lot of time in this network as we continue development. But before getting into details, I’d like to show you how to access the Regnet. To do this, it’s really similar to what we just did before and rather quick. So, go back to your Bitcoin core.conf file and remove or comment out with a hashtag where you wrote testnet equals one. Instead of this, right regnet=1. Now, save that off and restart the application again and it will load into the regnet. Again, it’s pretty simple but definitely not intuitive if you haven’t seen it before. Finally, to get back to the main net, you just remove all this information from the Bitcoin Core.conf file. You can do this by deleting the texts, commenting it out, or deleting the file completely. For now, I recommend commenting it out. It makes it quicker to jump between these networks in the future. This configuration file will continue to grow over time as we learn more about its functionality. Finally, you don’t need to actually create this Bitcoin.conf file yourself, you can do it directly from the wallet interface. To do this, from the wallet, navigate to Bitcoin core. Select “Preferences” and then choose “Open configuration file” from the bottom left of the pop-up window. We avoided doing this at first because you will need to first log into the main net wallet to get access to this feature. This will start sinking the main net blockchain and take up a lot of space you may have been trying to avoid by creating this file. All right. So that’s a wrap. That’s how you access each of the networks available for the Bitcoin Core client. When you’re done, you can close out the console or stay on and experiment. We’ll continue to learn more about each of these networks as we use them throughout the program.

11. Get Testnet Coins-Xytjo4JgKTo.en

While it’s exciting to have a test network up and running, we can’t do much if we can’t make any transactions. To make transactions, we’ll need test net coins. To get these coins, either someone could send them to you or you can go to what’s known as a public faucet. In this video, we’ll walk you through the steps to help you get test net coins using a public faucet. By following the steps in this video, you’ll have your first coins available in your Bitcoin core wallet. A Bitcoin faucet is a website that gives rewards in the form of Bitcoin. These faucets exists on both the test net and the main net. So yes, you can go to a faucet and get actual Bitcoins right now, but they don’t give you very much. It’s actually so little, it’s not actually worth your effort if you’re thinking of doing this for profit. On the test net, none of these coins have any value. So, you can use a faucet to get a decent amount of test coins to facilitate your test transactions. Let’s go ahead and do that. To start, load up your wallet in the test network. Remember that you can do this by typing in testnet equals one in your Bitcoin.configuration file and then restarting your application. Once inside your wallet, checkout the overview page to see how much Bitcoin you currently have. Now, unless you’ve been messing around with your wallet previously, like I have here, you probably see that you have a balance of zero, and there should be no transactions. Now, before we can receive testnet coins, we need to copy a receiving address from your Bitcoin wallet. To do this, go to file, and then receiving addresses. If you don’t have any addresses here already, you can always create a new one by clicking the “New” button. Give a label for your address. I’m going to name mine here “Public faucet test” and then hit “OK”. Once this is created, right-click on the address and select “Copy address”. We’ll be pacing this address into the public faucet that we’re about to visit. Now faucets come and go and there’s not really any one place that everyone should go to get their test coins. If you ever do you need to though, you can always search for the phrase testnet faucet and then just find one that you like. But for now, I like this one here provided by the Bitcoin testnet sandbox. We provided a link to this faucet down below the video. And it also comes up as one of the first options when you do search in Google. Alright. So, another way here, getting coins is really easy. All you need to do is paste your receiving address into the space provided here. If there’s a capture that says “I’m not a robot”, go ahead and click that. I don’t have one here already because I already used this. Then click “Give me some coins.” This starts the transaction and testnet coins should be available in your wallet just shortly. There’s a couple of things I want you to know about this website before we leave. First, like we mentioned, there’s a limited number of test coins that do exist. Even though they have no value, there are a way for the community to have access to coins that they can test with. Now because of that, you’ll notice that there’s a receiving address down here that you can send these tests coins back to when you’re done. In doing so, it helps the community and it’s really useful that’s your send your coins back that you’re no longer using back to this address. This will allow other developers to have the same access that you do right now and help avoid the need to create a whole new testnet for in the future. Secondly, if you saw the capture or the clicking “I’m not a robot” is to avoid spammers from taking all the testnet coins by quickly submitting requests over and over. You can also scroll down on the site to see a list of the previous transactions that have been made. Now, there’s nothing too interesting here but it’s worth mentioning. Finally, you’ll see the current balance of the wallet that is distributing the test coins as well as the amount that you’ll receive by having made the request. Alright. So, back in the wallet. Here you might see the pending request or it might have confirmed already. If not, it might take a little bit longer but if there really does seem to be a problem, check that you’ve submitted the correct receiving address and then try again if you haven’t received any coins. Here in the overview page, we can see the recent transaction that’s adding the testnet coins to your account. You’ll also see that your available balance has increased, which is now reflected in your total balance. All right. So, that wraps it up for how to get access to test coins using a public faucet. There were some extra details in here throughout the video since it was our first time walking through this so, it did take a little bit longer. In the future, remember all you need to do is paste your receiving address into the faucet and you should quickly get some new coins. Coming up, we’ll put these coins to use by making our first wallet transaction.

14. Block Explorer-D5QYtjoa4Mk.en

Now that we’re making transactions for ourselves, we can check out the details of them using an online block explorer. In this video, we’ll find the transaction we just made and go over some important details of a Bitcoin TestNet Block Explorer. There are few options that you can use to explore block chains, and there are reasons that you may end up with a specific preference of one over another in the future. But for now, we’ll be using this one for the website blockcypher.com because it has everything that we need. You can get there using the link that we’ve put down below this video. Before looking at your transaction, it helps to know what’s going on here. First, check to make sure that you’re on the Bitcoin TestNet. To do so, click on the drop-down and select Bitcoin TestNet from the list of options. Once you’re on the TestNet, you will see that the page is broken into three main sections; Recent Blocks, current Fee Estimates, and the Latest Transactions. For the Recent Blocks, you’ll see things like the height, the age, number of transactions, total Bitcoins sent, total fees, and the block size. These are hopefully pretty familiar attributes by now. Notice that the height is always increasing by one, and the age of each is more recent than the last and that’s because it’s listing each block in the order that they’re being created. The total amount sent and the fees are dependent on what was specified by the user making the transaction. The transactions and the size are related to one another. More transactions in the block means more data is stored on the block, which results in a larger block. Scrolling down, you’ll see the current fee estimates. This is a way to see the proximate cause of making transactions on the network. This isn’t too important right now, since these are all just TestNet coins, but as you start making applications, the transaction fee can definitely impact the way users might send and receive Bitcoins with your app. Finally, down at the bottom here, you’ll see the latest transactions that have been made on the Test Network. Now, if you were to go to this site quick enough right off you send your transaction, you might be able to see your transactions on the list. But if it’s not there that’s totally fine, you can always look at your transaction using the search bar here. Let’s go ahead and do that now. To search for your transaction, you need the transaction ID. So, back in the wallet here, go to the Transactions tab, and then right-click on the transaction that you’d like to search for on the Block Explorer. Select the option Copy Transaction ID, and then navigate back to the Block Explorer, and then paste this ID into the search bar, and then click Search. Here, you’ll see all the details of your transaction, with things like the amount, the fees, the time, and the number of confirmations it has received. The advanced details shows you things like the block hash, height, the index, and a number of other details. Scrolling further down, you’ll see the detail section. This gives a breakdown of the transactions inputs and outputs. You can see that the original transaction was initiated by sending this much, but then only the amount requested was sent, and the remaining amount was given back to the sender as change. So, that’s most everything that you need to know about finding your transaction on the Block Explorer. This is a good tool for navigating the network and getting a good idea of the structure of data available on the block chain. Keep in mind that all of this data can be access programmatically as well. Now, as you look around, think about how you might want to use some of this information in upcoming applications as you build.

15. End Of Lesson Motivation-SZ86RNrwucg.en

Howdy, everybody? So, we’re back with Brandy. And we just covered a lot about Bitcoin core and learned a bunch about the different types of networks. With that, why is it important that we know that these different networks exists and what should we know about them? Well, if you haven’t noticed, it’s really about focusing on the development cycle for applications, and there’s so many different stages when you develop an application and that’s why we have different network types. So, there’s times where you want to use regression testing because you need to stay in your silo, within your own little development sandbox. Once your new application starts maturing and you want other folks to be able to interact with your application, that’s the power of the testNet,. You don’t have to sit there and expense large value to do a transaction with a testNet. It’s like a free resource for the development communities. I really love how that bring so much reward to the developer with the testNet. And that’s why we utilize blockish pool, so we can actually see that transaction line on the public network with the testNet, and then we have the public mainNet, and that’s for production because that’s where you’re going to actually expense solid value with that transaction. So, you want to be really cautious and also pay attention to security. Yeah. I think it’s really exciting that we have all these different environments that we can play with and different reasons for using them, and it’s important, especially as a beginning developer, to keep in mind like you mentioned, as we’re going through the development process, to know when is the best time to use each of them.

16. Lesson Recap-HScAH1fiRF0.en

Alright. You made it to the end of the lesson. In this lesson, we discussed an overview of the Bitcoin Core Networks then, compared Mainnet, Testsnet, and Regnet. We set up a Bitcoin Core Full Node Wallet, obtained Testnet Coins and lastly, completed and explored a transaction. Getting comfortable with these tools will help you complete your next project, where you’ll build your own private block chain. And in the next lesson, you’ll build on these skills and use commands in the debug console to explore components of the block chain. When you’re ready we’ll see you there.

img

Part 03-Module 01-Lesson 03_Bitcoin Debug Console

01. Lesson Introduction-Hw9viNPtLEI.en

Welcome to this lesson on the Bitcoin Core Debug Console. Previously, he worked on the testnet and create a transactions using the user interface of your Bitcoin core wallet. While this interface is a great start, the real power comes from being able to access this information programmatically. You can do that using what’s known as the Bitcoin Core Debug Console. Throughout the lesson, we’ll discuss many of the commands available to you in the debug console. Our goal is to help you get set up to confidently explore blockchain data using this tool. We’ll do this by covering commands for each component in the block chain framework. This lesson builds on everything you’ve learned so far. It’s where this program really starts to turn from conceptual ideas to the lower level nuts and bolts you’ll need to build an application. Don’t worry, we’re not going off the deep end here and we’ve really tried to make this lesson in a way that’s relatable, approachable and allows you to be prepared for more advanced topics later on. Also, there’s one really important thing we want you to get from this lesson, that will take a little effort on your part. In this lesson, you’ll have a huge opportunity to type the data you’re seeing to the conceptual ideas we’ve talked about earlier in the program. For example, when looking at block data, think about how this relates to what you understand a block to be. What images in your head already? How does this data relate to that image? Putting in the extra effort here is going to allow you to visualize how all this connects. This will become invaluable as we start building more complicated programs later on. We put a few more details below the video. If you’d like, take some time to read through and when you’re ready we’ll see you in this lesson on the Bitcoin Core Debug Console.

02. Debug Console Motivation-N5mbG7aTwpY.en

Hey, everybody. I’m back with Brandy and before we get started in this next lesson, I had a couple questions. We are choosing to focus a lot on the Bitcoin debug console throughout the lesson, and I was wondering what made you decide that this was important to learn and how does it help the students? Yes, excellent. So, the debug console is really another tool for us in our toolbox for discovering new services within blockchain. Now of course, every platform has their own toolset, right? Right now, we’re discovering the world of Bitcoin Core and how we can work with the blockchain for Bitcoin course platform. And the debug console allows us to explore and that’s where I really love about the debug console. All right, cool. And another question before we get started that I had, is we’re focusing a lot so far in this program on Bitcoin specifically, but that’s not the only blockchain out there. There’s tons of other options and we actually playing on exploring some of them later in the program. Particularly, Ethereum, and I was wondering, how does some of the stuff we’re going to learn about the debug console now translate into what we’ll be doing with Ethereum later? Yeah, that’s a fantastic question, and this is something I’m actually excited about. You know, you don’t really appreciate the toolset until you see the power of the tool working and that’s what we’re doing at the debug console and right now, we’re focusing on Bitcoin cause it’s literally the first generation of blockchain services. Bitcoin created blockchain, right? I mean, obviously, it’s an underpinning of the technology and now we’re seeing the power of it as we’re navigating board to second generation blockchain services and that’s the Ethereum platform, second generation with smart contract. So, what’s interesting is we’re going to see a lot of these commands that we’re utilizing now within the debug console also participate with the Ethereum platform and it’s super nice because we get to utilize the same concepts with other platforms. So, we have Ethereum, but there’s so many more out there that we can experiment with. So, it’s really nice to know that there’s always something to experiment with to understand what functionality really exists with that platform and it always starts with one way to discover functionality and the debug console is a fantastic way to do it. Great, thanks. Yeah, it’s been really exciting seeing all the connections between the different platforms and how related they actually all are. So throughout the rest of the lesson out, we’re going to be talking about the debug console and we hope you’re excited to get started.

04. Debug-Console-Overview-RfK9a-pxZWA.en

It’s possible to explore Bitcoin data not only from websites and block explorers, but directly from a command line. Understanding how to do this is a huge step towards programming your own blockchain applications. In this video, we’ll familiarize you with one way to do this using the Bitcoin Core Debug console. We’ll introduce some of its core features and get you started with a few of its commands. The debug console assist with debugging efforts and provides a window to the Bitcoin Core RPC console. The RPC console is essential to back-end services with Bitcoin blockchain. It also allows you to investigate the blockchain as new blocks are introduced. Now let’s go ahead and start using it. To access the console, first go to your Bitcoin core client. From there, navigate to help in the top menu bar, then select debug window. Here you should see a screen similar to ours welcoming you to the console. It also includes a warning message about being cautious when running commands. We recommend that while testing these features, you continue to use wallets that are not connected to any actual Bitcoin value. Please be careful. If you’re connected to a wallet that is not storing information, there should be no problems with experimenting using the console. Down at the bottom of the screen, you’ll see a place to input commands. This is how you interact with the console. A great way to start is with the help command. Select the command prompt, type “Help” and click “Enter.” What you see now is all of the available commands, you can use to navigate the blockchain with this tool. There’s a lot of commands here, but to help you out, they split them up into a few main categories. These categories are Blockchain, Control, Generating, Mining, Network, Raw transactions, Util and Wallet. Note that whenever you see something following the command and the help menu, it means that the console is expecting some extra input from you to return the information you request. Each of these commands are pretty clearly laid out to allow you to easily experiment based on what you’re interested in. You can get the details on any of these commands by typing Help, followed by the name of the command. We’ll use the Help function pretty extensively as we review these commands in more detail throughout the lesson. Try a few of them for yourself to get more information about any of the commands on the list. So there’s some basics to get you started with the debug console. This is a really interesting tool that allows you to explore a ton of data on the blockchain. Remember, the Help command is your best friend here. You can always use this to explore more information about each of these commands, but we’re definitely not done walking through the different commands available. We’ll be going through more of these throughout the lesson.

05. Blockchain Commands-qnA32eDW4hE.en

When getting started with the debug console, it’s interesting to see that you can access data about the entire blockchain. In this video, we’ll cover three commands you can use to explore the blockchain using the Bitcoin Core Debug Console. The commands will cover are getblockchaininfo, getblockcount and verifychain. The goal is for you to be comfortable exploring these commands and understanding the basics of what information they provide. This will be important later as you begin using these commands to build your own blockchain applications that need access to this type of data. Feel free to follow along as we work through each of these commands. Let’s get started. First, getblockchaininfo returns various state information about blockchain processing. This is a great first step to get an overview of the entire bitcoin blockchain. Using the help function, I can see it returns information, like the chain, blocks, headers, and many other details. Now that I know what to expect, over on get blockchain info in my console. Here you’ll see the values for each of the fields that we saw before. We can see that we’re on the test chain. There are this number of blocks, this number of headers, and so on. When looking in your console, you’ll probably see different values than I do. That’s because the blockchain will continue to change over time, so things like the number of blocks will continue to grow. This command also shows you a few interesting things like the BIPS, hard forks or soft forks that have happened on the chain. Here’s an example that comes up, BIP66, for this BIP, we can see the version and whether or not it was accepted to the network. In this case, it says the reject status equals true, which means that this was never implemented into the protocol. Scrolling a little lower, we can see BIP9 which includes two main updates, CSV and segwit. You can learn even more information about the forks shown here on the Bitcoin BIP GitHub page. We’ve linked that below the video. If you’re interested, check out what CSV was meant to improve to better understand the effect it had on the blockchain. Next, we’ll go over getblockcount. This command returns the number of blocks you’ve synced to your local copy of the blockchain. This is helpful in situations where you’d like to know how far along you are towards syncing to the network. Using the help function, I can expect what this command will return. Here it shows that it’ll simply return a number. I can run this command by typing getblockcount into the console. Here, the console shows me that there are this number of blocks in my current blockchain. This is actually something you saw already in getblockchaininfo the difference here is that this specifically returns the number of blocks where get blockchaininfo returned this data along with tons of other information. Finally, the command verifychain, allows you to verify the blockchain database. Using the help function, you can see that this will return true or false depending on if the blocks you specify or verified. Running this command can take a bit of time as the debug console runs through the entire history of blocks to check and verify them. As you can see, when I run this, it returns true meaning that everything on the entire chain is accurate. When you do this, it doesn’t look like much, but it’s actually pretty amazing what it’s doing. It’s running through the entire history of transactions on the blockchain and checking to make sure that every block is valid. This is what we mean when we keep saying that everyone in the peer to peer network has the power to verify information, and with this command, you get to do it for yourself. That wraps up a quick overview of commands you can use to inspect the blockchain. The commands we covered were getblockchaininfo, getblockcount and verifychain. The commands allow you to explore this type of functionality, but also empower you to provide this type of data to users of your own blockchain application. Feel free to experiment with each of these commands to help you get a better understanding of the blockchain

06. Hash Commands-yFHlPV3NCiA.en

Hash values underlie the entire structure of the blockchain. In this video, we’ll cover three commands you can use to explore hash values using the debug console. We’ll cover getblockhash, getnetworkhash per second and getbestblockhash. Having access to these hash values will allow you to run more complicated commands later on to inspect the details of the blockchain. First, we’ll cover getblockhash. Getblockhash returns the hash of a block at the block number you provide. Accessing this hash value will allow you to further inspect these blocks with a few commands we’ll be reviewing throughout the lesson. Using the help command, you can see that you’ll need to provide the height, also known as the block number, for a block. There’s not much more to this one, so let’s try it. I’ll type, getblockhash followed by the block I want. I’ll try block 19. What we get back is the hash of this block. You can choose different blocks to get back different hash values depending on what you’re looking for. This may seem simple but it’s an extremely powerful way to access information throughout the blockchain. Next, let’s look at getnetworkhashpsps, ps stands for per second. This command returns an estimated network hashes per second based on a specified number of recent blocks. The network is creating hash values as quickly as possible and this is broken down into hashes per second using this command. You can use this any time you might want to check the speed of the network. Using the help function, I can see that I need to provide the command followed by a number of blocks. This input will be the number of recent blocks that we want to calculate the hash for. I’ll run this command checking the past 150 blocks. We can also check the last 100 blocks to see the difference. Finally, the last 50. So, we can compare between the three. Notice the difference between each of these. Using this, you can start to get a feel for when the network was operating slower or faster. Since each hash is happening at a different rate, it can’t give an exact value for this, but it can return the average. That’s why you’re choosing a certain number of blocks to calculate the average from. Finally, getbestblockhash returns the hash of the best block. The best block is a term you might not be familiar with. What it is, is the most recent block that you’ve synced to your local copy of the blockchain. There may be a thousand blocks that exist in the network, but if you have currently only synced everything up to block 100, then block 100 is considered your best block. Knowing that, we can check this out using the help function. There’s not too much interesting going on here. This return value is similar to getblockhash. Instead of choosing a block, it will default to giving you the hash of the most recent block. Now, run getbestblockhash. What we now see is the value of the most recent block that is synced to our blockchain. That’s all there is to it. That wraps up our overview of some of the commands you can use to explore hash values using the debug console. To recap, we covered three commands you can use. These commands were getblockhash, getnetworkhash per second and getbestblockhash. Try practicing these commands for yourself to help get more familiar with how hash values are represented on the blockchain.

07. Block Commands-sDEFdyUZ0FE.en

Now that we have the hash values of a block, we can start to further explore blocks on the blockchain. In this video, we’ll cover three commands you can use to explore blocks in the debug console. The commands we’ll cover are getblock, getblockheader and generate. These commands will be extremely useful to help you access data about specific blocks on the blockchain. To start, let’s look at getblock. Getblock returns details of block information, the amount of detail returned can vary depending on the level you specify. This allows you to pull any of these details into applications you might create in the future. Using help, you can inspect the details of this command. What we need to provide is a block hash. Then we can specify whether we want a string of data, an object with block information, or the same object along with each transaction in the block. This is specified using 0, 1 or 2. Let’s try running this command. First, we need to get a block hash. We can do that by running getblockhash and choosing a block number. I’ll pick 100. Putting this hash into the getblock command, we get details like the hash, confirmations, size, and much more. Running this command and selecting 2, we’ll see that the transaction has been broken out into even more detail. We now also have information like the hash, version and size. This is a lot of information, so feel free to pause the video and take time to inspect the data it has returned. Next, we’ll cover getblockheader. getblockheader returns information about the header of a block, just like it says. This allows you to call more specific information in cases where you don’t need access to all the block details you get from getblock. Running this using help, you’ll see that this returns all the details of the block, but doesn’t include transaction information like before. I’ll run this in my debug console, but first I need to get a block hash again. I’ll use getblockhash and choose block 19, because it’s my favorite number. I now have a hash I can use to put in to getblockheader. Next, I’ll run getblockheader and paste the hash from black 19 into the command. Now you can see the details of the header for this block, but don’t have access to the transaction information. Finally, let’s go over the generate command. Generate allows you to immediately mind the specified number of blocks to an address in the wallet. This is a way to create blocks that you can then interact with on the blockchain. This is extremely helpful for testing applications when you want more control over your environment. This command is actually only really useful on the regnet. The regnet allows you to create blocks instantly since there is no network that needs to verify any of these transactions. I’ll switch over to the regnet now. Remember, to do this, type regtest = 1 into your bitcoin.config file. Then reload the software. Using the help function, you’ll see that it allows you to specify a number of blocks to generate. Once I do, the console will instantly create this number of blocks on the regnet. Let’s try it. I’ll generate 100 blocks. What it returns is the hash for each of these blocks. I can now explore and work with these blocks just like any other that we’ve seen previously. Pick one of these values and run the command getblock to see more details of any block you’d like. All right, so there’s a few commands you can use to get started exploring blocks with the debug console. We covered getblock, getblockheader and generate. If you like, continue playing around with these commands to create and inspect your own blocks using the debug console. Before moving on, remember to switch back to the test network. Throughout the rest of the lesson, we’ll continue going over more of the commands available to you.

08. Wallet Commands-0IkTtQfiaGU.en

In general, Wallets have feature limitations that can make them difficult to manage. With the debug console, you can gain access to additional features that are hidden from the user interface. In this video, we’ll cover three commands you can use to explore wild information from the debug console. We’ll cover getwalletinfo, listwallets, and walletspassphrasechange. These commands are extremely important when configuring Blockchain services. First, we’ll look at getwalletinfo. getwalletinfo returns various information about the state of a wallet. This is a helpful way to access wallet balances and other metadata. Using the help function, you can see that this will return details about the wallet name, version, balance, and much more. Try running this command for yourself by typing getwalletinfo. As you can see, the name of my wallet is wallet.dat. This is the standard wallet name and yours is probably similar. It also shows that I’ve made zero transactions and sadly that I have no money in my wallet. If you’ve been playing around with your wallet and doing transactions, it might show something else here, and that’s fine too. Next, we’ll check out the listwallets command. This command returns a list of currently loaded wallets, meaning anywhere that you have available under your account. Using the help function, we can see that this is a pretty straightforward command. It tells us that we’ll get back a wallet name and provides a few examples. Let’s try this by typing listwallets. What I get back is the same wallet.dat that came up using the previous command. This isn’t too exciting yet, but it becomes more useful in cases where you start managing multiple wallets. This will be common as you start building applications to test transactions between them. Or if you have other reasons to manage multiple wallets for yourself. You can also check to see that this is correct by navigating to your main bitcoin folder. What you see here is the wallet.dat that’s being read from the debug console. Finally, let’s look at walletpassphrasechange. The purpose of this command is to change the wallet passphrase from its current passphrase to a new one. You might remember this passphrase as the 12 word phrase you used when you originally created your wallet. This helps you do things like recover your wallet in the case that you forgot your password. Using the help menu, you’ll see that this command expects you to provide both the old passphrase and the new passphrase along with the command. I’m not interested in updating my passphrase right now so, I’ll leave this command alone. I only wanted to mention it to show you that things like this are possible. To quickly recap, we just walked through some of the details of three helpful commands you can use related to wallets. These commands were getwalletinfo, listwallets, and walletpassphrasechange. These will help you manage wallets you create when building applications or when checking out your own personal wallets.

09. Mempool Commands-pd_lMZDjXOY.en

The debug console can help us learn the status of any transaction that has been performed and can also provide insight into the size of the mempool. In this video, we’ll utilize the debug console to explore the current state of transactions within the mempool. We’ll cover three commands related to the mempool. getmempoolinfo, getrawmempool, and getmempool entry. These commands help you access transactions that haven’t been added to the blockchain yet. First, let’s look at getmempoolinfo. getmempoolinfo returns details on the active state of transactions in the memory pool. This is a quick way to see some basic mempool information. Using help, you can see it return to things like size, bytes, usage, and other information. Let’s run the command to see what we get. Here we can see there are currently this many transactions in the mempool taking up this much space. If your node hasn’t been fully synchronized yet you won’t see any of the information for transactions pending in the mempool that’s because you’re wallet downloads the existing transaction history before moving on to the mempool. So, if you don’t see anything when running these commands it might be because your wallet is still synchronizing. In this case, just wait a bit longer and try this command out once the blockchain is fully synced. Next, let’s try a new command, getrawmempool, getrawmempool returns a list of all transaction IDs in the memory pool. Using the help function, we can see the output will return the transaction ID, size, fee, and other important mempool data. Now, try running this command yourself by typing getrawmempool. If it doesn’t show up in your console, it could again be that you’re not fully synced to the blockchain. Just wait a bit longer and come back once the mempool is synced. What you’ll see is a long list of transaction IDs. You can check out the details of these transactions using a few other commands. One way to explore these transactions even further is by using getmempoolentry. This command returns mempool data for a given transaction. Using help you can see that you’ll need to provide it with a transaction ID from the mempool. You can use one of the transaction IDs that we just saw when we ran getrawmempool. So, let’s try it. Type getmempoolentry then paste one of the IDs in after this command. You might notice that this actually returns an error saying the transaction is not in the mempool. This is one time where it’s helpful to really understand the concepts to better understand what’s going on here. If you remember, the mempool is just the waiting place for transactions before they get accepted into the blockchain. What that means is that the transaction ID you just saw a minute ago might have been accepted into the blockchain in the time it took you to run getrawmempool with it’s ID. In that case, you’re getting an error because you’re looking for a transaction that’s not in the mempool anymore. To get around this run getrawmempool and try to quickly inspect this transaction with getmempoolentry before it gets accepted into a block. So, that wraps up some basic commands for getting started with the mempool. To recap, we just went over getmempoolinfo, getrawmempool and getmempoolentry. If you need to, wait a bit longer for you’re wallet to sink then try exploring the mempool for yourself once it’s ready.

10. Transaction Commands-7LHsSJ_9dik.en

While it’s generally don’t give access to transaction information beyond the ones you made personally, but using the debug console, you can explore details of transactions from across the entire network. In this video, we’ll cover three helpful commands related to transactions that you can perform in the Bitcoin Core debug console. The commands we’ll cover are getchain transactions stats, getrawtransaction, and listtransaction. Transactions are at the core of everything that happens on the blockchain, and getting access to this information will be invaluable as you begin putting this type of functionality into your blockchain applications. To start, let’s look at getchain transaction stats. Getchain transactions stat or getchaintxstats returns compute statistics about the total number and rate of transactions in the chain. This is a great way to get an overview of all transactions that are happening on the blockchain. Using the help function, you’ll see that this returns information like the time, transaction count, block count and other statistics about transactions. Now, try running this command in your console by typing getchaintxstats. We can see that the timestamp of the final block is here, there are this many transactions and there’s about this many transactions made per second. Next, let’s look at getrawtransaction. Getrawtransaction allows you to look at the details of any raw transaction data. A raw transaction is a transaction that is formatted to be readable by computers. It follows the rules of the Bitcoin protocol to process the human readable transaction and turn it into a single value that can be interpreted by a computer. Having access to raw transaction data is the first step towards being able to create or manipulate these transactions. Let’s look at the details of this command using the help function. As you can see, to run this command, you’ll need to provide a transaction ID. Let’s try that. A quick note on this command is that it defaults to accepting transactions and the mem pool. So, to get our mem pool transaction, we can type in getrawmempool. From this list of hashes, pick one as the input for getrawtransaction. Now, type getrawtransaction, paste in the transaction id and follow this with the word true. Using true, allows you to see more information about the transaction. When you’re done, run this command and see what you get. What you’ll see first is just a huge string of numbers containing information like the hash, version, size, and other useful details. This is a lot of information, so if you’d like, pause the video and take a look before we move on. For our last command, let’s look at listtransactions. Like you might expect, this gives us a list of transactions for a given account. This is helpful if you ever want to explore transactions that have been made by a given user, or if you want to present this data to a user with your application. Using the help function, you can see this returns the account, address, category, amount or other details about a given set of transaction information. You can provide this command arguments like the account, total count of transactions, and any transactions you’d like to skip. To run this command, type listtransactions into the console and what you’ll get back is a list of all the transactions for the account you specify. The default is your own account, and I don’t have any transactions on this account, so it’s just showing up as an empty array. Yours may also be blank but once you start working with transactions, this empty array should start to fill up. To quickly recap, we discussed three helpful commands you can use to explore transaction information. These commands were getchaintransactionstats, getrawtransaction and listtransactions. These commands will be very valuable as you start working with transactions while building your blockchain applications.

11. Signature Commands-T6M-RC7NmXc.en

As a blockchain developer, you’ll use transactions as a means to transfer value. Every transaction that’s adopted in the blockchain need signatures. There are commands that provide a way to create signatures programmatically. In this video, we’ll cover some helpful commands related to digital signatures you can perform in the debug console. The commands we’ll cover are signrawtransaction and signmessage. These are a little more complicated than other commands and we’ll be getting into much more detail on transactions later in the program. This video is just meant to introduce you to some of the commands you can use without getting into too much detail. First, we’ll cover signrawtransaction. This does exactly what it says and allows you to sign the inputs for a raw transaction. The only difference between a transaction and a raw transaction is that a raw transaction is formatted to be readable by computers. It follows the rules of the bitcoin protocol to process the human readable transaction and turn it into a single value that can be interpreted by a computer. We’ll be using this later in the program as we start to create and sign transactions for our applications. Using the help function, you can see that this command takes in quite a bit of arguments and can get pretty complex. Reading a little more detail, we can see that the second and third arguments are optional. This allows us to simplify the command a bit at least for now. Using only the required commands, what we need is a transaction hex string and a private key. Running this on a transaction that has already been processed results in an error. Since I don’t have any unsigned transactions right now, I can’t run this command. But here’s a quick overview of how to get a transaction hex string and a private key in case you’d like to piece this together for yourself. To get a transaction hex string, first use getblockhash to find a block, then use getblock to find a transaction within that block. Finally, choose a transaction from the block and input this to get raw transaction. This returns the hex string for that transaction. Using this and a private key, you now have the inputs for signrawtransaction. You can get your private key using dumpprivatekey. We haven’t covered that yet but it’s a pretty simple way to get the private key for your wallet. Dump private key needs you to also give an address. You can get this by going to File, Receiving addresses and then creating a new one or copying an existing address. Now, paste that after the command and what you get back is a private key. Like I mentioned, I’m not running the signrawtransaction command, but this should give you at least some of the tools to start exploring this for yourself. Other commands involving signatures also get a little more complicated similar to signrawtransaction. Some of these commands are sign message and sign message with private key. These generally involve getting hold of some information about the wallets and transactions involved and piecing them together to sign a message. Transactions are at the core of many blockchain applications, we’re just touching on these commands briefly for now, but future lessons will expand on the creation and signature of messages much more. To recap, we discussed some helpful commands that you can use to explore signature information. We went over some details on how to navigate the signrawtransaction command but didn’t get into too much detail on how to execute it. This was mostly to make sure you’re familiar with these commands but without getting too far into the details. If you’d like, use this as an opportunity to explore these commands for yourself. You’re hopefully pretty familiar with the help command at this point and you’ve gotten most of the information you need to go ahead with these commands yourself. If you’re not sure how to do this or would rather move forward, that’s fine too. We’ll jump back into a few new commands in the next section.

12. Network Commands-zvlKHHRHn5o.en

The Bitcoin network is made up of a peer-to-peer network of computers that allow information to be shared across users. With the debug console we can query the level of pure connectivity and even modify our peer list. In this video we’ll explore the peer-to-peer network using three commands, getnetworkinfo, getpeerinfo, and getconnectioncount. These are useful when we want to connect to other users, or understand the connections we’ve made with other users in the network. It might not be so clear why yet, but this is extremely useful when configuring backend services with multiple nodes. We’ll be doing this type of work later in the program. For now, we’re mostly hoping that you’d get some exposure to these commands so later we can focus on how to use them in your application. Let’s get started with getnetworkinfo. You might be noticing a pattern here. Just like getblockchaininfo, and getmenpoolinfo, getnetworkinfo allows you to get a high level overview of the network you’re currently on. This is a helpful way to get basic information, and sanity check that everything’s working correctly. Using the help function, we can see that it will return information about our network like the version, subversion, protocol version, and much more. Read through some of the details provided in the console, then try running it for yourself. I’ll run it here by typing getnetworkinfo. Here, we can see that the subversion is Satoshi 0160, going down a little further, you’ll see the networks we’re on. In this case, ipv4, ipv6, and onion. A lot of this has already been provided in the information panel. You can go there by clicking up here on the top left. This information might not be something you use for your application, but here’s an example of a way you could use it. The Bitcoin Core wallet is pulling this information similar to how you just did, and it’s presenting it to you on the user interface. It’s a nice way to provide quick access to some of the more important information your users might need. Next, let’s try the command getpeerinfo. This command returns data about each connected network node. Also known as your peers. Having peer Info allows you to see the details of the users in the network. This helps you check to see who you are connected to, and the details about their connection. This can be useful in situations where you’d like to add or remove peers, or work with the information provided to you about them. Using help, you’ll see that this will allow you to get information like the ID, adress, and services for every node that is connected to the network. I’ll try it now by typing getpeerinfo, you might notice that the output is pretty large compared to our other commands. That’s because the data we get back is a separate group of information for every node we’re connected to in the network. As an example of how you might be able to display this information, you can check out the peers window in the console. When I click on peers, I can see the node ID, service, ping and other details of each node in the network. This is all the same information that’s presented in the get peer info command. So, when we talk about the peer to peer network, we’ve been mentioning it mostly as a concept. What’s cool about this is that it’s the first time you’re seeing some of these peers, and what information is available to investigate the different nodes. Finally, let’s look at get connection count. This command returns the number of connections you have to other nodes in the network. It’s nothing fancy, but it’s just another way to get information about nodes you’re connected to. Using the help function, you can see that there’s not really much to it. So, let’s run it and see what we get. Right now, it’s showing that we have eight peers. This might not seem like much, but it’s another example of information you can have access to that you could potentially provide to your users. We haven’t been giving exact use cases for each of these, because it depends on what you’re making. But to get a little creative, maybe I’d want to build a social network app where the nodes I’m connected to are considered my friends. Using a command like this, I can show people how many friends they have. Just making that up, we’re not totally focused on applications yet, but hopefully thinking of ideas like this can help you pull through some of the less exciting commands. As a final note, you can see each of these peers over in the peers window like before. It doesn’t show account, but since it’s pretty small I can easily see that it’s correctly showing me that I have eight peers connected to me. That wraps up the three commands you can use to check out the network. To recap, we covered getnetworkinfo, getpeerinfo, and getconnectioncount. Feel free to explore these commands as you continue to expand your network.

13. Mining Commands-mxR_LjHbQx0.en

The Bitcoin Blockchain currently uses miners and proof-of-work to achieve consensus. Using the debug console, we can check out information about miners on the network. In this video, we’ll cover two commands you can use to explore mining info using your debug console. We’ll cover getmininginfo and prioritisetransaction. These commands are a great way to get an overview of the state of each block, it provides ways to use block data that might help you with creating and testing applications later on. First, let’s look at getmininginfo. getmininginfo returns an overview of mining related information, this helps you understand some pretty interesting things like which block is currently being worked on by a minor. Using the help command, you can see that it will return the current block, the weight of the last block, transaction information and more. I’ll run this now by typing getmininginfo. Here it shows we’re currently on this block along with some other information. If you’re still wondering why the blockchain is so large to download, here’s a good example of why. Even being on the test net, we’re still sync to over 1,000,000 blocks, with each block being around two megabytes, this can easily take up a lot of space. Another command I wanted to show you was prioritisetransaction. This command accepts a transaction into mined blocks at a higher or lower priority. This means that you can control the likelihood and order that transactions will be accepted into blocks. Having this type of control can be very helpful later on when building and testing your applications. Using the help function, you can see that it needs three inputs to run, the transaction id, a dummy value and a fee_delta. This is a little more complicated than other commands. This may come up again in testing, but we can avoid running it for now. I just wanted to mention this command to show you that this type of thing is possible. One thing you might notice is that prioritise is spelled with an ‘S’ where normally I’d spell it with a Z, that’s common in the UK and it tells us that whoever came up with this was likely from there. Given that Satoshi Nakamoto is still unknown, maybe this is a clue that they are from the UK? You never know. We might just find them someday using clues like this, but anyway, there’s some of the commands related to mining. To recap, we just went over getmininginfo and prioritisetransaction. These types of commands will be very useful as we begin creating our own applications. Feel free to explore these further, before moving on to other commands.

15. End Of Lesson Motivation-0PnZfuhU2PE.en

Alright. So we just wrapped up learning a ton of new commands that you can use in the debug console, and honestly it can really be a lot. There’s dozens of commands probably. I was wondering, when you use it, is there any command in particular that you found particularly helpful? That’s great. I mean, you just got done saying it right, helpful. Anytime that I need to discover new functionality on any blockchain platform, the very first go to command for me is help, and you can see that right there in the debug console. Just type in help, and it’ll list all the available functionality in regards to console you can make for the Bitcoin Core Platform. It’s the same similar thing you can do with other platforms, like Etherium, hyperledger, stellar, it just goes on. So help is by far my favorite command to use. Yeah. No, I definitely used it a time. There’s a couple of other commands I like too. I find it interesting when certain commands string together. So it’s like, to get block, you first have to get block hash and then you can sort of trace back to an original core idea. I find those helpful, but whenever I get lost in that, I go straight back to help too. So yeah, definitely very great command for me. It reminds me of a time where we were experimenting with some of the commands, you remember I was going along route like, I would go ahead and get a raw transaction right and I would get the information and then I would perform another command to go ahead and translate that to human readable tags like, “Hold on, Brandy, you wouldn’t believe what I just discovered”, and you showed me how to go ahead and do that all in one command. That was super cool. I just figured it out by using help. Perfect. So there we go, favorite command, Help. Thanks Brandy. You’re welcome.

16. Lesson Recap-WmH9zO0UUSE.en

All right. You made it to the end of the lesson. In this lesson, we discussed the Bitcoin Core Debug Console. We also walked through many useful commands for each of the core block chain components. Hopefully, you’re comfortable enough to explore these further and look through a few more of these on your own. Another goal we mentioned was that you take some time to understand how the concepts we described earlier are being represented by the data shown with these commands. If you’re able to tie the concepts to the data, you’ll be in a great spot as we move on to more complicated topics. This lesson also helped prepare you to complete the next project. We will use this data to build your own private blockchain. In the next lesson, we’ll continue to build on these skills. For more details on the upcoming lesson, feel free to read through the text below the video. When you’re ready we’ll see you in the next lesson.

img

Part 03-Module 01-Lesson 04_Blockchain Data

01. Lesson Overview-uDpiatdaKQw.en

Welcome back to class. So, far in the course, you’ve learned a lot about Bitcoin core, creating transactions in the wallet gooey, and cover a number of debug console commands. In this lesson, our two big takeaways will be understanding transactions and blocks as data models, and understanding how to use the information that’s stored inside of them. Any blockchain platform you end up working with will be transaction-based. Whether you plan on building your own blockchain or leveraging an existing blockchain, understanding how the data is structured will help you use it more efficiently. We’ll run up the lesson on a more philosophical note, discussing the ethics and best practices when embedding data in blockchain transactions. To summarize, by the end of this lesson you’ll be able to recognize the Data Structure of Blocks and Transactions, recognize the purpose of Bitcoin Script Opcodes and these are commonly used in the inputs and outputs of the transaction process, and lastly explore the limitations and best practices of Embedding Data in Blockchain Transactions. Using these skills will help you with the next lesson where you’ll build all components of your own private simple blockchain off from scratch.

02. Blockchain Data Motivation-66ASaQxH0LY.en

So I’m excited to start off our lesson about block data. So, previously we were talking a lot about Bitcoin Core and how to use it as a tool. In this lesson, we’ll shift gears a bit and learn about data as it relates to blocks in transactions. So with that in mind, why is important to understand blocks and transactions as data models? Yes, the data models are extremely important to understand because we’re going to be paying attention more and more to the protocol and every time that we look at the protocol, we have rules with a way to interact with blockchain platform. We need to understand the data model so that way we know when to relate the data that we need with our application development efforts. So it’s really important to understand a data model so that way we can work with that data model. Interesting. So speaking of data, I know there’s ways to embed data into the Blockchain and that’s actually sort of some controversy. So for example in the bitcoin platform, some developers developed a way to embed data using operation codes are what’s called Op-codes into blocks. There has been a divide in the community where on one side people say the Bitcoin Blockchain wasn’t meant to stave off non-financial data. So, we’re inflating the blockchain and putting a heavy load on on folks who weren’t intending to do it. On the other side, the community saying, this is a way for the Blockchain to grow into spaces beyond financial sector. So, do you have thoughts on that? I do. You know it’s really interesting the controversy that goes on in community. Early on, folks would actually have to burn their Bitcoin to embed data, and this would inflate what we know as a UTXO database. So the sides would grow the ledger would be more expensive to maintain across the nodes. So, now we have a maturity existing within the protocol as new improvement proposals get embedded into the Blockchain and Op-code right like Op-return. You still can embed data but now they’re safeguards to help make sure that the UTXO database doesn’t inflate so much that it’s nearly impossible for a full node to download the ledger. It’s really still important to understand that the non-financial data is really best to be separate off in regards to the ethics of the way that we’re maintaining that dataset. Right. So, if we’re going to create a transaction and we want to store data because we love the immutability nature of a blockchain ledger. There’s some creative ways that we still can utilize a public Blockchain like even with Bitcoin. Well, we can take advantage that Op-return and embed a hash to prove that transaction exists. We don’t need to store a ton of data on a public ledger. You make a good point. I’m only talking about ethics, the idea of ethics. It’s not commonly a topic of discussion as a developer is actually a really important concepts especially as we’re developing across industries and the implications of that into those industries. So with that do you have any advice for students before they start the lesson. What you meant at a good point about like ethics, just being cautious about it. Anytime that we work with data, we do want to think about our ethical responsibility for the way that we’re handling data. Something that I think a lot of people don’t recognize is the value of understanding that privacy. Like we talked about before on unblocked and identity. Maintaining your identities it’s extremely important, and that should carry forward to the way that you do a transaction especially when you start embedding data utilizing Blockchain services. Will be ethically responsible and maintain that dataset that’s going to be mutually beneficial for everybody’s going to use your application. Yeah. So I’m really excited to talk more with you guys about this as the lesson continues.

03. Blockchain Data Models Overview-1BfheON7OY4.en

In order to understand how information is stored on any blockchain, we need to understand block and transaction data models. This will help you build up and structure your own private blockchain in the following project, as well as understand how to interact with existing information on blockchains. Earlier, we saw that blocks contain a block header with these important pieces of information, the Previous Block’s Hash, the Time the block was created, the Merkle Root and the Nonce. As we’ve explored before, the body of the block contains transactions. In the next several sections, we’ll expand on transaction data models focusing on transaction inputs and outputs, which will help us understand how to create our own raw transactions. No matter which blockchain you end up working with, it’s important to remember that blockchains are a transactional system. Having a good grasp of this information is vital to understanding what’s going on under the hood with any blockchain service you end up working with.

04. Inputs And Outputs-Lx_tKdZYMJg.en

No matter which blockchain you end up working with, transactions are the most important part of any blockchain system. You can think of them as the atoms of the blockchain space. So, just as atoms are the fundamental building blocks from which all life is built upon, transactions are the units on which blocks of data are built upon. As you may have noticed, everything in the Bitcoin blockchain as we’ve seen is designed to ensure a transaction can be created, propagated as the network, validated and then eventually added onto the blockchain. To understand how to build our own blockchain, we need to understand the nuts and bolts of a transaction. In this video, we’ll review how transactions work, focusing on their inputs and outputs. Having a good grasp of these concepts will be very important later when we discuss transaction data models. Transactions encode the transfer of value between participants and a system. In more detail, a transaction is a data structure that encodes a transfer of value from a source of funds called an “input” to a destination of funds called an “output”. Let’s take a look at a real life transaction we’ve explored before. This transaction consumed or used one input and created two outputs. Think of a transaction as a simple payment from one person to another, which often includes change that’s returned to the original owner. In this example, one user had about 0.0257 Bitcoins in their wallet, they then paid another user 0.015 Bitcoins and the rest point 0.0106 Bitcoins was returned back to the original owner as change. Now the question is, where do these inputs come from and where do these outputs go? So, here’s a simplified diagram of a single transaction. Let’s call it Transaction A. Bitcoin transactions are composed of inputs and outputs. In a transaction, the inputs are just the unspent outputs from another transaction. For example, if there’s a Transaction B, it’s inputs maybe one of the outputs from Transaction A. Let me repeat that last concept again because it’s really important. Inputs in one transaction are just the unspent outputs from another transaction. All inputs reference back to an output. Conceptualize the arrow as a pointer from the inputs referencing back to the outputs from which they came. This is similar to pointers in a linked list, and you’ll find that this is a standard arrow notation of inputs pointing back to their outputs. When a user receives Bitcoins that amount is recorded on the blockchain as unspent outputs. Unspent outputs is often shorthanded to UTXO. UTXO is short for unspent transaction outputs. You may see both of these terms used interchangeably. Like we were saying, when a user receives Bitcoins, that amount is recorded onto the blockchain as unspent outputs. This means if the user has received lots of Bitcoins from several different transactions there is a huge UTXO recorded for each of these transactions. So, the user’s Bitcoins maybe scattered across the Blockchain. When it comes time for the user to spend their Bitcoins, their wallet scans the blockchain and aggregates all the UTXO belonging to that user and then calculates the balance. Said another way, there is no such thing as a stored balance for an account or a Bitcoin address. There’s just records of UTXO tied to a specific owner that are sprinkled throughout the blockchain. Another important thing is while UTXO can be any arbitrary value, once it’s created it is indivisible, just like a coin. It can’t be cut in half. If a UTXO is larger than the desired value of a transaction, it must still be consumed in its entirety and change must be generated in the transaction. Let’s take a look at an example. It’s Brandy’s lucky day and I’m going to send her two Bitcoins. My wallet scans the blockchain and sees that there are two UTXO associated with me that can be summed up and used for this transaction. The first UTXO has 1.25 Bitcoins and the second has one 1.75 Bitcoins. The wallet aggregates these to UTXOs to total three Bitcoins that we use as the input of my transaction with Brandy. Here’s what that looks like as a transaction input-output diagram. My wallet found UTXO tied to my address that can be used as inputs for this transaction. So, one UTXO that has 1.25 Bitcoins and a second that has 1.75 Bitcoins. The transaction processes and spits out two outputs. One output that is two Bitcoins sent over to Brandy, and another that sends one Bitcoin of change back into my wallet. If there is a minors or transaction fee, this is the difference between the inputs minus the outputs. This can be summed up all in this equation. Sum of the inputs minus sum of the outputs equals the transaction fee. That wraps it up for a quick recap of transaction inputs and outputs. We covered that transactions are a data structure that encodes a transfer of value from a source of funds, what’s hot an “input” to a destination called an “output”. We saw that inputs in one transaction or just the unspent outputs from another transaction, and outputs are the amount received or transferred in a transaction. This amount is recorded in the blockchain as UTXO, which is short for unspent transaction output. These concepts will help us in the next section as we deconstruct an actual transaction data model.

05. Transaction Data Models-ukArkoSPbT8.en

We saw that a transaction consists of inputs and outputs. Now, in the world of bits and bytes, how is this information stored in the transaction data model? Let’s explore the pieces of data that make up a transaction. On a blockchain, transactions are stored in a double hashed form. This means, the initial raw information is put through SHA-256 twice. If you were to ask the network to return back to us a raw transaction, we likely get this. This is called a raw transaction because it’s still in hexadecimal format and hasn’t been decoded into a JSON object yet. It might seem a bit hard to decipher but it’s actually quite organized. We can break it apart to understand how the protocol layer stores our transaction information, so that we can efficiently leverage it when building our own botching. All transactions contain these pieces of information. There’s the version. All transactions include information about the Bitcoin version number so we know which rules this transaction follows. An input count, which is how many inputs were used for this transaction. Next is input information. We’ll go into more detail about everything that’s contained here but at a high level, there is information about where the input is coming from, and checks that the input can be used. In output count, which tells us how many outputs were produced from this transaction. Next is output information. So, similar to input information which will be discussed in greater detail later, it tells us how much Bitcoin was outputted from this transaction, and has conditions that allows them to be spent in future transactions. Lastly, we get locktime. The locktime field indicates the earliest time or the earliest block a transaction can be added onto the blockchain. If the locktime is non-zero in less than 500 million, it is interpreted as a block height. Remember, a block’s height is the number of blocks in the chain between it and the genesis block. So, the genesis block has a height of zero. If a transaction locktime is a block height, miners have to wait until the licit block height is reached before attempting to add the transaction onto the block. If the locktime is above 500 million, it is read as a Unix Timestamp which means, the number of seconds since the date January 1st, 1970. So our time is usually zero which means confirm as soon as possible. Let’s go back to the input and output information sections. Part of what’s contained in the input, and output, and froze are scripts that are instrumental to how a transaction gets signed. A script is just a computer program or a set of instructions inside each transaction that is executed to decide the transaction is valid. The transaction input contains an unlocking script, and the transaction output contains a locking script. If the transaction is valid, this means that the unlocking script has the requirements that unlock the conditions of the locking script. Now, scripts are a fascinating way to express complex conditions. You may have heard of smart contracts before. Smart contracts are nothing more than a series of conditions that must be met for an action to occur, and the parameters that meet those conditions. Now, scripts allows to do just that. As we continue this lesson, you’ll learn more about the power of scripts that allows us to fine tune and control how transactions are executed onto the blockchain. Let’s do a quick recap. We reviewed that the block header contains these parts. It has the Previous Block’s Hash, the time of creation, the Merkle Root, and the Nonce. Afterwards, we looked at the transaction data models inside the block which contained the version, the input count, input information, the output count, output information, and the locktime. We also mentioned that the input information contains something that’s called an unlocking script, and the output information contains the locking script which are used to validate a transaction. Next up, we’ll see exactly how this is done.

06. Bitcoin Scripts-Ed4Jb_Reb_4.en

In any blockchain platform, from Bitcoin to Ethereum, transactions hold a lot of vital information for the network to run. We use block explorers to view the inputs and outputs in a Bitcoin transaction. In addition to this information, we also learn that transactions include small bits of instructions called scripts, that allow the transaction to process. In this section, we’ll understand the purpose of scripts, using Bitcoin scripts as an example. Then, we’ll discuss specifically unlocking and locking scripts, checking out what’s their purpose, how do they work, and working to find them in raw transactions. Now, let’s start with scripts. A script is just a list of instructions recorded in each transaction that when executed will determine if the transaction is valid and the Bitcoins can be spent. Bitcoin scripts are written in a scripting language called Script, and that’s with a capital S. Quite a tongue twister, so say that three times fast. A scripting language is a simple lightweight language designed to be limited in scope, and executable on a range of hardware. Bitcoin script is a stack-based language, this means that the data is stored in a simple data structure called a stack. You can imagine it similar to a stack of playing cards. The stack commonly stores numbers or data constants. We interact with information in the stack using operators which shorthanded to opcodes. Operators can push or add information onto the stack, they can pop or remove information from it, they can also act on information in the stack, as well as push results back onto the stack. When you see a script it will execute from left to right. Now, that sums it up for Bitcoin script basics. Now let’s discuss the unlocking script and the locking script. What are their purposes? How do they work? Where can we find them in raw transactions? As we’ve mentioned before, inside a raw transaction we can find the unlocking script and the locking script inside the input and output information sections. At a high level, the scripts are small programs inside each transaction that are executed to decide which transaction is valid. If the transaction is valid, it can be signed, and a transaction can go through. These two scripts work together, similar to a puzzle edits solution. For a transaction to be valid, the unlocking script will solve the locking script. Locking script is like a puzzle that specifies the conditions that must be met before the Bitcoins can be spent. The unlocking script contains the correct solution that solves the puzzle and evaluates the locking script to ”true”. Here’s an example of Bitcoin script. It’s okay if these items don’t make sense just yet, we’ll cover them later in more detail. This is just for your reference for what scripts could look like. Bitcoin clients validate transactions by checking that the unlocking script solve the locking script. Here’s how that works. Remember that inputs from one transaction refer back to the unspent outputs from another transaction. For each transaction, the validation software retrieves the UTXO referenced by each input. Each UTXO has a locking script that contains conditions required to spend it. In other words, each UTXO contains a puzzle that needs to be solved in order for the input to be spent. To check that the transaction is valid, the validation software grabs the unlocking script contained in the input, and checks if it solves the puzzle of the locking script. Now, let me stop and call a common point of confusion. Note that the unlocking script in a transaction does not unlock or interact in any way with the locking scripts in that same transaction. Instead, the unlocking script of an input interacts with the locking script of an output from a previous transaction. The locking script in the same transaction interacts with the unlocking script of a future transaction. Now, let’s take a look at how the locking script itself works. A locking script places a lock on an output by specifying the conditions that must be met in order to spend the outputs in the future. In a simple example, let’s say my transaction output contains a script that says, ”This output is payable to whomever can present a signature from the key corresponding to Brandy’s public address.” Since only Brandy has the wallet with the keys corresponding to that address, only Brandy’s wallet can present the signature in order to redeem this output. In Bitcoin, historically the hash locking script was saved in a variable called scriptPubKey, because they contain a public key or a Bitcoin address. So you might still see this phrase used in most Bitcoin app source code. However, the phrase locking script is more encompassing of the broader possibilities allowed in the scripting technology. So, here’s an example of scriptPubKey used in Bitcoin source codes, wallet.cpp file. The unlocking script in our puzzle analogy is the solution that will solve the puzzle. It satisfies the conditions of the locking script and allows the output to be spent. A common way it is implemented is that the unlocking script contains a digital signature produced by the users wallet from their private key that will unlock the locking script. Historically, the hash unlocking script is stored in a variable called scriptSig because it usually contains a digital signature. So you might see this phrase still used in most Bitcoin app source code. However, the phrase unlocking script is used because not all unlocking scripts must contain a signature. Here’s an example of it used in Bitcoin source codes wallet.cpp file. Now that we know more about scripts, where can we find this information in the transaction? Let’s go back to when we broke down the parts of a raw transaction, and said that the scripts are found inside the input information and output information sections. If we rear organize those values into this table, it’s easier to see which parts are the script values. You’ll notice a lot of fields that we’ve discussed before like version, input count, output count, and lock time. Inside the input information we can see the field scriptSig which we mentioned before is synonymous for unlocking script. Inside the output information we see the field scriptPubKey which is synonymous for the locking script. You’ll see these terms used when we look at raw transactions from the debug console later. So keep this in mind. I’ve added this breakdown of the raw transaction down below this video. Take some time to familiarize yourself with what sections they are. This will help you when it comes to creating your own raw transaction. In the next concept, we’ll be covering scripts in more technical detail.

07. C2L4 3.2 A Script Opcodes V3-4hZpoSLuFt8.en

In our overview about Bitcoin scripting language script, we learned that it utilizes operation codes or opcodes for short. Now there are actually 80 something different opcodes available to us when we’re writing scripts. In this section, we’ll learn more about how to use opcodes. Remember that script is a stack-based language and opcodes allow us to interact with data on that stack. Some opcodes exists that either push or pop one or more parameters from that stack, then act on them and then may push the result back onto the stack. For example, there’s OP_ADD and this is an ad opcodes. Notice the opcodes are prefixed with OP. So, OP_ADD will pop two items from the top of stack, add them and then push the sum back onto the stack. There are other opcodes that are conditional operators that evaluate a condition and then produce a boolean result of either true or false. For example, OP_EQUAL checks at the top two stack items are equal to each other. Let’s see an example script that uses these opcodes together. Here, we have 2,6 OP_ADD eight and OP-EQUAL. Remember, scripts execute from left to right. Starting from the left, the constant value two is pushed onto the top of the stack. The script continues moving to the right. The next constant value six is added on top of the stack on top of the value two. Next is the opcode OP_ADD. The operator ADD pops the top two items from the top of the stack. Here, which are two and six, adds them and then push the sum back onto the stack. In this case, eight is returned back onto the stack. Moving right, another constant value eight is push onto the stack. The last step is OP_EQUAL, which pops the top two items off the top of the stack. In this case, eight and eight and then checks that they are equal and then returns a boolean value of either true or false back onto the top of the stack. In this case, it’s going to be true. This simple arithmetic example can actually be a valid locking strip that can be used to lock a transaction output. This portion of the scripts could be the locking script. Six OP_ADD eight and OP_EQUAL and it could be satisfied by transaction containing an input with the unlocking script two. As we saw in the step-by-step example above when this script is executed the result is true making the transaction valid. This means the resulting UTX0 can be spent by anyone with the skills to know that the number two satisfies the script. This is a simplified case which will help familiarize you with script and opcodes. Later on, we’ll see scripts that make use of signatures and public keys and these constants can be used in the unlocking script. You’ll also see new opcodes used in the locking script. For example, there’s OP_DUP which duplicates the top stack items and this is a commonly used operation code and there’s also OP_CHECKSIG, which checks the signature for the top two stack items. You can find a complete list of opcodes and their descriptions in the Bitcoin Wiki which I’ve linked below. Try out the following quiz and solve for the unlocking script for the given locking script. This will help you practice working with the execution flow and logic in scripts.

09. C2L4 3.3 HA Attributes Of Script V2-RKx-JbvzMy8.en

Bitcoin Script is a simple stack-based language that offers a number of operations. It even has conditional flow control. However, there are intentional limitations built into it which we’ll be covering in this section. The goal of this concept is to familiarize you with the prominent attributes of Script. We’ll be covering Turing Completeness and Stateless Verification. Now, one major attribute of Script is that it is not Turing Complete. This means there are no loops or complex flow controls, other than conditional flow control. This makes the language completely deterministic so that we know when and how the program will end. Turing and Completeness removes the fear of being stuck in an infinite loop which could block or crash the network. A limited language prevents the transaction validation mechanism from being targeted and attacked as a vulnerability. Turing and completeness simplifies and secures the system. A second attribute of Script is that it is stateless. This means that all information needed to execute the Script is contained within the Script and no state is saved prior to running the Script, or after the Script has ran. The benefit of a Stateless Verification is that the same Script run anywhere in the system will execute the same way. So we can rest assured that a Script verified on our node, we verified the same way on another node. To recap, Bitcoin Script is not Turing complete and is stateless. These two properties allow the network to better scale and build insecurity. As you learn more about other bloc chains, you’ll encounter they’ve chosen to use languages with similar or vastly different properties. For example, instead of being stateless, they may be stateful, meaning they do have an internal state that allows for loops and recursion. This allows for more flexibility but limits Scale for trustworthy verification. As you approach new blockchain platforms. be vigilant to understand the strengths and weaknesses of each implementation.

11. Create Raw Transaction Motivation-ZWrgUK8OKLY.en

Hi, everyone and we’re back for Block Talk. We’re actually we are talking about raw transactions. So, as a reminder, raw transactions are how machines store off the transaction data. So, the lesson so far, we’ve taken a raw transaction and dissect it into its different parts, and now you understand the components of a raw transaction. I want to ask you why is it important as a Blockchain developer to know how raw transaction works? Isn’t a raw transaction meant for the computer? Yeah. It’s absolutely meant for the computer. I know we talked about before, we’re trying to hit home on the protocol, and that’s exactly what we’re doing with the raw transaction. We’re looking at the protocol, understand their roles on how to construct a transaction that gets embedded into the Blockchain. So, that life cycle of taking a transaction that’s human readable, breaking it down to be consumable by like the Bitcoin platform is extremely important in regards to the rules of the platform. That’s why we constantly are advocating about the protocol because those rules allow us to have guidelines for the way that we’re going to work with transactional data. We also understand the nuts and bolts will really help us down the line. Oh, absolutely. Especially when it comes down to the way that we can work with transactional components of a Blockchain. It’s even better to understand that the same principles with a raw transaction also works on other platforms. So, the way that you broke down the transaction as a raw transaction is literally the same way that you would use it on another platform. You still need to go ahead and transact, especially when we migrate to back-end services. How does the network communicate with transactional data? It’s all about raw transactions. Yeah. It’s a really powerful way to think about it. So, with that, let’s start creating our own raw transaction.

20. Embedding Data In Transactions-I-r1mcjrII8.en

Earlier we discussed that blockchain is a type of database; a database where there’s no way to edit or delete information, but we can read, append and validate data. This begs the question, aside from transactional data, can we add other types of data onto the blockchain? If so, how is it done? Let’s take a look at the Bitcoin blockchain as an example. Even though it is possible to store data on the Bitcoin blockchain, the Bitcoin protocol was not designed for the purpose of data storage. However, as the blockchain expands beyond finance, many companies and individuals started embedding data with transactions in order to store non-financial data. Doing this, as you may have guessed, comes with risks and issues. A number of other newer blockchain protocols have risen in order to fill this need. Each hyper blockchain has its pros and cons as a data storage method including Bitcoin. In this section, we’ll discuss the best practices and limitations of embedding data on the Bitcoin public blockchain. Understanding the risks here will help us be more aware of the pros and cons when analyzing how other blockchains handle data storage.

21. Embedding Data In Bitcoin Core-FLDsIqFjT3w.en

In the early days of Bitcoin and the blockchain space, members of the community were testing out different ways to take advantage of the irreversibility of blockchain to store data. They figured out that it was possible to place information in a transaction scriptSig value that didn’t alter the end result of the running script. Users could take some data, hash it, and then embed the hash into the output. Now, this led to all sorts of data from photos of Nelson Mandela to prayers offered for miners to love notes being stored permanently on the blockchain. Not only did this lead to objectors arguing that it led to blockchain bloat because it was forcing full Bitcoin nodes to carry the cost of the storage for data that was not intended to carry. But, this also led to transactions with unspendable UTXO. It’s because UTXO had locking scripts that could not be unlocked. Because these UTXO could never be spent or removed, Bitcoin nodes will be forced to spend memory to carry them on forever. Bitcoin core developers introduced the Opcode, OP_RETURN which allowed 40 bytes to be used in an unspendable transaction, thus, bypassing the need to store them in the UTXO set. Even though OP_RETURN outputs are still recorded on the blockchain using memory, they aren’t stored in the UTXO set, so they don’t bloat the UTXO memory pool. Data using OP_RETURN is saved in the script in this format, OP_RETURN followed by the data. Often, the data is some hash the results from SHA256 hashing. If you want to take a look at OP_RETURN in action, checkout the first output in this transaction with the hash listed here. You can view this yourself by connecting to a full Bitcoin node, and then running the getRawTransaction command. The data after OP_RETURN is data that’s been hashed into a hexadecimal format. If we convert this hexadecimal to a string, we’ll see that converts to charley loves heidi. We’ve seen that it’s possible to embed data on the blockchain, as well as seen how it’s done. But, the question is, is it ethical and should it even be done? This is a controversial subject that we’ll explore more of in the next section.

22. Ethics Of Embedding Data-f89XGNgmJ6k.en

As we’ve alluded to storing non-currency data on a Blockchain where that wasn’t the intended purpose is a matter of debate in the Bitcoin community. Is it ethically correct? On the one hand, the Bitcoin Blockchain is a secure decentralized method for data storage on which applications beyond financial ones can leverage. Allowing data storage would help promote the growth and long-term relevance of the Bitcoin platform. Some in this camp believed that the Blockchain should be a public resource available for whomever to use as long as they paid for sufficient transaction fee for the miners. On the other hand, other community members believe the Bitcoin Blockchain should only be used for Bitcoin transaction data, and any other type of data should be stored separately. Regardless of which side of the debate you may fall, the importance of scalability issues cannot be avoided. Adding data to the network, especially network where data cannot be erased, raises the maintenance costs and adds a burden to everyone involved. Every time a four node downloads the Blockchain, all the data takes up memory that someone somewhere has to pay for.

23. Lesson Summary And Project Prep Overview-o2vU7kxjtRM.en

In this lesson, we explored the limitations and best practices when embedding data in blockchain transactions. To recap, you learned the data structure of blocks and transactions. You became familiar with the purpose of Bitcoin scripts and OP codes, which are commonly used in the inputs and outputs of a transaction. Then, you got the chance to dive into a real life raw transaction. Lastly, we discussed the limitations and best practices of embedding data in blockchain transactions. Now, that wraps it up for the new topics in this lesson. In the next lesson, you’ll bring together all that you’ve learned about blockchain data models to create a simple block chain all from scratch with your instructor. This hands-on practice will help you with the project that’s associated with this course where you’ll create your very own private blockchain. You’ll build a blockchain focusing on the collection of data and stringing together blocks via their hashes. This will be a low-complexity blockchain that doesn’t implement any formal consensus just yet. However, your blockchain will be able to create new blocks, store data within the blocks, and perform transactions, and secure the blocks with a digital signature. Now, with so much to do let’s get started.

img

Part 03-Module 01-Lesson 05_Private Blockchains

01. Lesson Introduction-L4yqJ3NrVzI.en

Hi, I’m Brandy. You’re doing a wonderful job in the program. I would like to welcome you to the next lesson regarding private blockchain. In this lesson, we will discuss usage of a private and public blockchain and how to interact between the two chains. By the end of this lesson, we will demonstrate building our own private blockchain ledger. We will utilize JavaScript and make use of third-party libraries with proven methods to support cryptographic functions. To help you get started, would put a few more details about this lesson down below the video. If you like, take some time to read through and when you’re ready, we’ll see you in the next lesson on private blockchains.

02. Public And Private Blockchains-7prXCvNo6hc.en

Public blockchains can serve as a backbone for nearly any democratized solution whether verifying identity, helping Internet users gain control over their data or enhancing collaborative efforts. Public blockchains are at the front line of the revolution because of their permissionless design that allows anyone to participate. In course one, you learned the value of identity management with your private and public keys and wallet addresses. With course two, you were introduced to the public testnet. This is a great example of a public blockchain. All of us are able to participate without needing permission. It’s pretty clear the power of a public blockchain, but what does it mean to be a private blockchain? In this video, we will discuss the essential difference between public and private blockchains. We’ll compare them based on four atributtes; their permissions, scalability, vulnerability and compliance. Let’s get started. First, let’s look at how permissions differ between these blockchain types. Public blockchains are open and permissionless allowing anyone to participate or benefit from the technology. For example, bitcoin is known for its creation of a blockchain with public protocol. This allows for users to build and run their own peer-to-peer transaction network without building their own ecosystem. Anyone can participate. This is the driving force behind public blockchains. The success of bitcoins public protocol led to create a new platform, which foster an open ecosystem with a public protocol. One of these platforms has become very popular, is known as Ethereum. This is known as the second generation of blockchain services and you’ll be learning more about this later on in our program. Unlike public blockchains, private blockchains require permission to access and typically operate under centralized control. Let’s look a little more into private blockchains starting with scalability. Private block chains benefit from efficiency in terms of scalability and compliance with regulatory requirements. The drawback with a private permission blockchain is the vulnerability of its network, where bad actors could potentially manipulate its dataset due to vulnerabilities of centralized governance. While private blockchains have low transparency, meaning they restrict information from being seen by the general public, they also rely on their limited private networks to maintain the integrity of the blockchain itself. Public blockchains on the other hand are permissionless and can be maintained by anyone with sufficient computing power to do so. The public openness allows for full transparency of the information they contain. The biggest drawback of public blockchain is scalability and regulatory compliance. For instance, with Bitcoin Core, transactions on the public chain are time-restricted with new blocks being added to the chain about every 10 minutes. This restriction improves security and controls supply yet impacts scalability of transactions the platform can process at any given time. As far as regulatory compliance, a public blockchain lacks centralized control. When new laws are created by local governments there is limited ability to adopt those laws. To recap, we just compared the difference between private and public blockchains, a quick overview of permission types, Scalability, Vulnerability and Compliance. For more details, it’s best to review developer documentation for the platform you’re interested in. Understanding the difference will help you know when it’s best to apply a public or private blockchain depending on your use case.

03. Public And Private Blockchain Interaction-rNANX-FF6tI.en

At first glance it almost seems impossible to communicate between private and public blockchains, due to the vast difference with permission and permissionless blockchain protocols. To help understand how this communication works, we’ll look at an example where we need to store public blockchain data into our private blockchain. Let’s imagine that our private blockchain needs to log Bitcoin transaction activities. Our logger service would monitor new blocks added to the public blockchain. The transactions within the box would be logged into our private chain utilizing transaction hash as a link between public and private blockchains. To store private blockchain data into our public blockchain, we would need to reference the options available to us by referring to the platform documentation. In this case we will use Bitcoin core. Previously we discussed the usage of operation codes. One operation code that allows us enough storage to store a hash value is OP return. Typical hashing algorithms generate hash values less than 40 bytes. For example, SHA256 Hash is 256 bits long. To reduce its size under 40 bytes, we can encode the data to binary with eight bits per byte. Using binary we would achieve 32 bytes for storage of the hash. OP return allows us the option to store a hash value that references our private blockchain dataset. As you might have noticed, the hash allows us to utilize its uniqueness as a unique ID to reference and connect our data between blockchains. There’s two quick examples of methods to link public blockchain to private blockchains, and ways you might consider doing it. In the end both examples depend on a transaction to occur. Connecting data between blockchains is also known as cross chain functionality. Cross chain functionality allows a series of protocols to work in harmony to deliver decentralized applications. We are entering an age where new projects are focusing on ways to develop cross-chain protocols that tackle the task of interacting between chains. A project example is Polkadot. Polkadot is configuring itself as a intermediary between blockchains. Polkadot uses a multi-chain approach with a blockchain called Relay which coordinates consensus and transaction delivery between blockchains. Next Polkadot utilizes a second blockchain called Parachain which gathers and processes transactions. Finally, both solutions together create a bridge that links to blockchains with their own consensus such as Bitcoin and Ethereum. So, that wraps up this discussion on public and private blockchain interactions. In this video, we discussed private, public blockchains and ways to communicate between blockchains utilizing hashes. We also provided a project example to allow intermediating between blockchains as a dedicated service to promote cross-chain functionality. Cross-chain functionality is an important concept to understand and very similar to the way that we relate data with traditional databases which require a unique ID. After all, a transaction has is also a means to establish a unique ID.

04. Building A Simple Private Blockchain-F0NiiTTJstc.en

In a previous lesson, you learned to discover a blocks content using Bitcoin Core. We navigated down the path of what a blockchain block looks like. Each block contains a header describing the core information about the block. Next, we have the body of the block which contains the data. Each block chain platform has a data model which is restricted by the platform protocol. We are now going to navigate down the path of creating our own simple blockchain which will allow us to navigate creatively, past transactional information within the block’s body. We will have the ability to control our own data model. The important thing is that the blocks are chained together using hashes. Let’s start with the creation of our blockchain block data model.

06. 03.1 SC Block Data Model-rAQK2Qgrtpo.en

To kick up our project, the very first thing we’re going to want to do is open up a new terminal session on the bottom right panel of workspaces like New Terminal. Within this terminal, we’re going to want to navigate to our project working directory. Don’t worry, we created this for you. If we go ahead and issue the command list structure, which is LS, press enter, you’ll notice that we have a project working directory called Project_2. We can utilize the command change directory to navigate to that project working directory. To do this, we just simply type in cd for change directory, and then we type in the name of our directory. Fantastic. At this point, you’re going to want to go ahead and initialize your project by issuing the command for the node package manager initialization, npm init, that stands for node package manager initialization. Once we have that configured, go ahead and press enter to kick it off. Now, it’s going to prompt you for a few questions specific to your project. Feel free to accept the defaults because at anytime, you can go ahead and edit the contents of this file. So, we’re going to go ahead and accept the defaults. All right. You’ll notice that it produce an output in JSON format. We kind of figured so considering the name of this file is package.json. We can see that right here. Okay. So, now that we have our package.json configured, this allows us to store project dependencies within the package.json for future installation of this project on other machines. Super useful. Okay. Now, to kick things off, to create our own private blockchain, we’re going to want to create our blockchain data model, and that means that we need to look at what a block looks like. So, let’s go ahead and take a look at an existing block on the testnet. On the left-hand panel of your screen, you’ll notice we have Project_2 in your file explorer. Let’s double-click it to open the contents. We have our package.json, and then we have testnet_block_1325438. Let’s go ahead and select testnet_block so we can reverse engineer the data model and simplify it for our means. Let’s go ahead and select everything inside this file so we can go ahead and create our own data model. To do that, I’m going to go ahead and select the entire contents of this file and then copy it. What I want to do is create a new file. I tend to use touch. So, down in the terminal window, I’m going to issue the command touch and I’m just going to call this notes.txt. Okay. Perfect. You’ll notice in your file navigation window on the left panel of your screen, we have notes.txt. We’ll open that file by double-clicking on it and it’s empty. So, what we’re going to do is now paste the contents from our clipboard to this file. The screen bigger. Okay. So, now, let’s go ahead and remove the data that we don’t need for our data model. Remember, we are building a simplified private blockchain, meaning there is no need for a consensus algorithm at this time. Let’s go ahead and remove everything other than the hash, the body of the block, the block height, the time that the block was entered into the chain, and of course, reference to the previousblock on the blockchain. So, what we’re going to do is remove everything that we don’t need. So, we don’t need anything that’s referencing to the consensus algorithm, we’re just going to delete those. The body of our block, we don’t need any data within it because all we care about is constructing your own private chain block data model. So, right here, we’re just going to remove all this data with inside the transaction body also known as a block body. Matter of fact, let’s just rename tx with body. All right, perfect. We’re going to remove merkleroot version. No need for weight, size, or confirmation, and let’s remove the data from the hash. Let’s reset the block height to zero; the time, zero; and previousblockhash, nothing. All right. That pretty much concludes what we’re going to need to start constructing our own private blockchain. Now that we defined our data model, let’s go ahead and add that to our notes. Block and data model. Perfect. Well, that concludes our block data model. Next up, let’s go ahead and create our own block constructor to support building out our private blockchain.

07. 03.2 SC Create New Blocks-Ma96H_3_Pjw.en

Within our notes, we have saved the Block Data Model. This is a great start to our project goal of constructing a simple private block chain. Next, we will need it to implement our block data model. To kick things off, let’s create our JavaScript file to start the creation of our private block chain. Let’s use touch to create a new file. For our JavaScript file, let’s go ahead and call this simple chain. So, we’ll type in the terminal, touch simpleChain.js. At this point, we know our data model will be reuse. JavaScript provides many methods to construct a reusable object for us. For example, we will utilize classes. The class syntax does not introduce a new object oriented inherent model to JavaScript. It purely provide syntax sugar. Our first step is to find our block class, also known as class declaration. So, to do that, let’s jump in to simple chain to construct our block class. On the left-hand side of your window, also known as the left panel, you should see simpleChain list. Double-click on simpleChain.js to open it. Perfect. Now, on our top panel within our window, we have notes and we have simpleChain.js. So, within simpleChain.js, let’s go ahead and start constructing our block class, class Block, and yeah, that’s pretty much what a class looks like, right? Nothing fancy here. Next, we want to establish a class constructor, which is a special method for creating and initializing an object created with a class. For each class, only one constructor can be created. Our block constructor will initialize our block object. So, let’s go ahead and put that into play. Constructor and we have no option for the constructor at this point in time. All right. To keep things tidy, I’m just going to go ahead and press tab to provide some indentation. Within our constructor bracket, I’m just going to add a space because I already know that we’re going to want to establish variables within our constructor. Matter of fact, next, let’s go ahead, and navigate back to our notes, and copy our block chain model. We’ll copy our block chain data model. Then, what we’re going to do is paste that within our constructor. Next, let’s go ahead and clean things up a little bit. We don’t need the open and close brackets since we already have that within our constructor. We’re going to delete those, go ahead, and highlight our variables, and provide an indentation. Now that we have our data model within our constructor, let’s configure our constructor define class variables. This is also known as scope. Our current scope is the class Block. When you define scope variables, in our case, we’ll change the hash, height, body, time, and previousblockhash to variables within our scope. To do that, we’re going to simply clean up our variable and put in this. This just means this scope and the scope is our block. So, we are going to do that for each of our variables. Great. That looks much better. Let’s modify our constructor to support construction on variable option for block body called data. So, here’s our constructor. Within it, let’s define a variable called data. Once we construct a new block, we want to go ahead and store data within the block body. So, let’s go ahead, and remove our array bracket right here, and put in our constructors variable called data. At this point, let’s test our block class. Within a terminal session, type node to enter node environment. Go ahead, and copy our block class, and paste it within our node terminal session. Let’s go ahead and press enter. We have a response undefined. That’s because our class has been created, yet it has not been defined yet. To use the block class, we can assign it a variable or call it directly. Let’s test directly, testing various data options. Remember, at this point, our class constructor only supports one variable called data. To test, we simply call a new object by typing new, followed by the class name along with constructor options for data variable. So, to do that, we’re simply going to type in new, Block. Then, within the Block, we’re going to have “Some Data”. Now, if I press enter, we’re going to get a response that a new block object was created and you’ll notice that some data was passed right along to the body of our block. Wonderful. Now, let’s go ahead and test with some different type of data like an array. So, I just press the up arrow to repeat the last line. This time, let’s just go ahead and put in our array. Here, we’ll just test various options. Sure enough, that array pass right on through to our body. Well, we can do the same thing with an object, and I’m sure that most of you already have this down, and very familiar with defining variables with new objects, but it’s nice to see them in action. Great. At this point in time, you have copied a block data model. Modify the block data model to suit our private block chain needs. We then created a simpleChain.js file with a block class that has a constructor, that shapes the variables for the class, for our new block.

08. 03.3 SC Store Blocks-ntVc-pXXa5A.en

Now, that we have our block class, we now need to construct our blockchain to store blocks. Before we make further modifications, let’s go ahead and make sure to add comments to our existing code. I’m going to go ahead and paste the code block N. All right. So, now we have our block class set to class with the constructor for the block. We can proceed forward. Let’s add a new blockchain class called Blockchain. Just like our block class, we can configure a constructor, constructor. Perfect. Now, that we have our constructor, let’s go ahead and utilize an array to store our blockchain. Let’s call this array chain. Next, let’s go ahead and add our comment banner. Perfect. So, at this point, we have a blockchain class with the constructor that stores data within an array. Let’s go ahead and new functionality to add a block to the array. Let’s go ahead and call the function addBlock. Within the function, let’s go ahead and call the variable a newBlock. Within our function body, let’s go ahead and add the new block to our chain. We’re going to say this chain.push newBlock. Perfect. Let’s go ahead and test within our terminal, utilizing a Node environment. Remember, before we went ahead and did this with the creation of our block class, let’s do it again with blockchain. Also we have to do now is copy our Blockchain class, and we’ll paste it right here within our Node environment and sure enough that’s been added within our Node environment. Next, let’s go ahead and test. Let’s stand to aid our object and assign it to a Blockchain variable. Next, let’s add a new block to our blockchain utilizing our addBlock method. We’re just going to put in some test data, nothing big. All right. To view the data within it, all is what we have to do is view the blockchain array, and with that we can call blockchain.chain. To recap, we created a new Blockchain class with a constructor to store data within side the chain array with a new addBlock function that allows a new block to be pushed to the chain.

09. 03.4 SC Linking Blocks-45q3-1n2RcE.en

Our next task is to secure blocks in a chain. We plan to utilize the SHA256 algorithm to produce the hash value for a block data. There are several libraries available to us from third parties for our Node.js project. For this project, we plan to utilize crypto-js. Let’s exit our node environment and install crypto-js using Node Package Manager. To exit the node environment, type in period and then exit. Let’s restructure just to verify that we have our files available to us, more specifically, package.json. Earlier in this lesson, we’ve displayed initializing the project utilizing Node Package Manager which created the package.json. We want to utilize the save flag to save crypto- js as a dependency for our project. Let’s perform that now. The response from Node Package Manager is providing a couple of warnings. The first warning is that, there’s no description for a project. The next, is that our project is missing a repository film. We can investigate this further by opening our package.json file. Let’s go ahead and do that. When we open the package.json file, you’ll notice that we have a new field called dependencies. Within dependencies, we have crypto-js that’s been recorded for us. Great. Now, we have crypto-js library available for us within our project. Let’s go ahead and navigate back to the Node environment. Type in node, let’s close the package.json file. Within our simple chain.js, let’s navigate to the top of our file. We need to configure a constant variable called SHA-256. To do that, we’ll type in const which stands for constant. We’ll call it SHA256, and will require crypto-js library referencing to the SHA256 algorithm. Within our block class, let’s modify our addBlock function to include the generation of our BlockHash. We need to call our newBlock and we’re going to reference to our hash value. Next, we’re going to go ahead and call the SHA256 library and then we’re going to pass it our value, construct our hash. To do this, SHA256 requires a string of data. So, we’re going to go ahead and utilize JSON, and we’re going to stringify the object. That object is going to be our newBlock. Then, what we want to do, is take that response and turn it into a string. Next, we need to configure a reference to the previous Block. The previous Block might not exist which is why we need to construct a conditional statement to check if the chain contains data. Above our newBlock hash, let’s go ahead and establish our conditional statement. If this chain length is greater than zero, we need a reference to our newBlock object and we’re going to go to the previous BlockHash. This.chain, and let’s get the previous object in the chain. We’re going to go ahead and put minus one because the array length starts off at one versus zero. So, we’re going to go ahead and subtract one, so it can start off at zero. Now, we’re going to reference to that object’s Hash. Now, that we have generation of our BlockHash with a reference to the previous BlockHash, it’s time to configure our Genesis Block and make sure that it’s always included at the beginning of the array. To do this, we will utilize our Blockchain Class constructor. Underneath our chain array, let’s go ahead and create a new Genesis block. We’re going to type in this.addBlock. To utilize our addBlock function, we’re going to go ahead and create a newBock and within that newBlock, we want to add some data that references to our Genesis Block. Let’s call this, “First block in the chain”, and then we’ll make sure that we reference this as the Genesis Block. Excellent. This is a great time to test our code. Within our command prompt, let’s go ahead and make sure to test code within our Node environment. Because we exited out of our Node environment, and then we re-entered the Node environment, we need to make sure that we paste the entire code of our file. Perfect. Now, it’s time to test. We need to go ahead and create a Blockchain variable and instantiate our Blockchain. Now, let’s test by adding a new Block. Let’s view the contents of our Blockchain array. In our previous BlockHash, it’s reporting an error and it looks like that I neglected [inaudible] provide camelcase values. Looking at our constructor, it looks like that that’s actually an easy fix. Since we notice an error during testing, let’s go ahead and exit out of our Node environment, copy our code, re-enter a Node environment and paste it in. To exit, we type ”. exit”. Then, to re-enter, we just type in node. Within our script file, we’ll “Select, All”, “Copy”, and we’ll “Paste” that in. Excellent. Let’s test. As you can tell, testing provides great value as you’re developing your project, because errors are going to happen. So, let’s go ahead and make corrections once when they’re discovered. Excellent. We corrected the issue with the camelcase value for our previous block. Our Blockchain has the first Genesis Block with the unique hash value. There is no previous BlockHash, therefore it’s empty. Our next block on the chain has a unique hash value and it’s referencing to the previous BlockHash, which is our Genesis Block. Let’s go ahead and add another block to the chain to verify that the chain is staying consistent with the way that is linking between hashes. We have our Genesis Block, our next block, and our most recent block. Each block is taking the hash value from the previous block. To recap, we configured the SHA256 algorithm utilizing crypto-js library, that has been included as a constant variable at the top of our simple chain.js file. Within our Blockchain class, we modified our constructor to include the new Genesis Block. Next, we modified the addBlock function. We made sure to include a conditional statement. Next, we go ahead and define our hash value for the block by taking the data, converting it into a string and then passing the response as a string to our block’s hash. Then, we add the block to the chain.

10. 03.5 SC Block Height With Timestamp-3n2TKw4_sIo.en

Now that we have our blockchain working where our blocks are being linked together with the previousBlock in regards to the BlockHash, now we need to look at adding additional functionality such as block height and the block timestamp. So, let’s go ahead and implement that now. Within our AddBlock function, let’s go ahead and add a new line, and this time let’s go ahead and call our newBlock object, and we want to reference to the height. To get our block height, we’re simply going to refer to our means of storage. In this case, it’s chain. So, we’re going to say this.chain, and we’re going to reference to the length of that chain. Perfect. Now that we have the chain.length, let’s go ahead and add a timestamp. Same thing, we need to refer to our newBlock. Now, we’re going to go ahead and reference to our time variable. Now, to get the date, we’re going to use a built-in function called Date. So, let’s go ahead and create a new Date object, and we’re going to want to get the current time, and we want to convert that to a string, and then next we want to slice that string and remove the last three characters from the string. That will allow us to have a compatible UTC timestamps that we can verify with external resources. Okay, perfect. Now, this is a great point to test our cone. We would like to go ahead and add a newBlock to the chain, we want to see the block height increment, and then we would like to see the timestamp be unique. To do this, we need an external node environment and re-enter the node environment, pasting in our newly modified cone,.exit. Wonderful results. Now, our blockchain is configured to add the block height, and this case, block height is zero for our Genesis block, we have a unique timestamp for that Genesis block. Next, we have the block height, one, incrementing up with a unique timestamp, and we can see that that is continuing to move forward; that’s the exact results we’re looking for. To recap, we modified our AddBlock function to include block height within our newBlock object. In addition, we configured our newBlock object to include a timestamp that’s following the UTC format.

11. 03.6 SC Level Db-Z-1Zq_i6Pls.en

We created a simple blockchain where blocks are stringed together utilizing SHA256 hashes. I modified our code to include additional comments, it’s best practice. I wanted to take time to prepare you for some challenges ahead. One of those challenges is persisting the dataset. At this point in time, your blockchain remains a memory with the chain array. Upon restart of your node project, the data state does not persist. Let me show you. Let’s navigate back to our terminal session to install level using Node Package Manager. So, we’re going to type in npm for Node Package Manager, install, level is our package dependency for this project, and then we want to go ahead and do —save for our flag to save this package dependency within our package.json project file. Great. We have LevelDB-wrapper installed. A prepared levelSandbox.js which is located as a resource for you to review. Let’s walk through it. We need and not require our project dependency called level. Next, we establish our storage location for the dataset, and then we could figure db as an object to reference to level with our chainDB which is the location of our dataset. We created a new function to add data to LevelDB with a key value pair. Our next function, we get data from LevelDB utilizing the key, and finally we addDataToLevelDB utilizing a value. This is a helpful function that loops through the key value dataset utilizing the createReadStream on data that loops through, and once in the loop has closed, it adds data utilizing the addLevelDBData function with the key and the data’s value. We can test using a self-invoking function. I created one here as an example. The self-invoking function has been defined as theLoop. We have a timeout configured that set for 100 milliseconds. This loops for 10 times. Feel free to test. Test by copying your code, going back into a node environment, pasting your code, and sure enough, new blocks were added, and then on the left-hand side, we have our chaindata where our dataset is being stored. To recap, we went through simple.js and we just added some comments to our code. Next, we’ve went through levelSandbox.js. LevelSandbox.js is just one means of expressing the power of LevelDB as a key value data store to persist our data state.

13. Lesson Recap-YvK4L6mqxO0.en

Congratulations! You created your own private blockchain. As you notice, it’s pretty simple. We have a blockchain that stores blocks linked together in a chain as a dataset. Some additional options you might want to consider to improve your private blockchain would be the addition of a peer-to-peer consensus algorithm. To recap, we just compared the difference between private and public blockchains and ways to communicate between blockchains utilizing hashes. We continue the journey with the creation of our own simple private blockchain without the difficulties of consensus.

14. Project Prep-1y9HFrJy_H0.en

We need to add functionality to validate the blocks and process the data set when the Node.js application is restarting. In your next project, you are tasked with a few challenges. The first challenge is to process the data set utilizing level DB. Next, add functions to support block validation. We wanted to keep it fairly simple so we started you off with some boilerplate code. Don’t get too excited. Even with boilerplate code you will still need to implement functions that support the project requirements. The boilerplate code contains comments to assist you in the success of your project. Good luck and we will see you in the next course.

img

Part 03-Module 01-Lesson 06_Building Your Own Private Blockchain

img

Part 04-Module 01-Lesson 01_Planning a Web Service

01. C3 V5-k4c8BMpQL4g.en

What’s a web service in the context of the blockchain world? So, a traditional web service it’s just, you’ve got a server and you may have some front in front of it or some API gateway and then clients will query that server and get back data right as it will render in the browser or they will consume it at the command line or via program and do something with it. The difference in the blockchain era is a web service’s back-end is no longer just a Postgres or MySQL database often in the cloud, but it can also include a decentralized blockchain backend or multiple de-centralized backends. Notice that, web service in the era blockchain doesn’t have to only have a blockchain based backend but just another backend, it’s a sheared backend that multiple different actors can read from and if they spend digital currency can write too. So, that’s what a web service is in the age of blockchain it’s got usually both the original Postgres based backend and it can tap into one or more blockchain based de-centralized backends. So, do companies in systems need to rewire the entire stack to take adventure blockchain technology? In some cases yes, because what a blockchain represents is a completely new payment rail and whether the complete new payment rail is completely different often regulatory environment and a completely different degree of risk tolerance for the business. In my view, relatively few companies that are Finance 1.0 or Wall Street 1.0 will be able to make the transition successfully. If you look at what the internet did, it has basically disrupted traditional books, newspapers, movies, Music, and relatively few of the incumbents are still around today in the same form like Blockbuster was disrupted by Netflix and Kodak was disrupted by Instagram and the digital players have different economics and cost structure and they came up in a different way. I think blockchain has that same revolutionary potential. Now with that said, some of the incumbents were smart and they did at least play it a good defense. The New York Times for example has a very good website, many of the Music and movie companies eventually did get into streaming simply some defense and I do expect some of the existing financial incumbents to play defense right? So, the banks and when they’re smart enough that they are working on blockchain based things. But it’s not core to them, they weren’t built on the blockchain and they’ve got 50, 70, 100 years of legacy that they have to deal with the theme of the New York Times still has log in contracts because it’s still doing paper news. Something that’s built on a blockchain has a fundamental agility and advantage sure that’s something that’s a legacy business doesn’t have, that’s why it’s challenging but not impossible for companies to rip and replace or augment their existing payment systems with blockchain.

02. Lesson Overview-JZlIkZYVbqc.en

Welcome to the lesson on planning a Web service. Previously, you learned how to create your own private blockchain. For a private blockchain to be valuable, it will need to integrate with the Web service so that the information is consumable for client applications. Think of it this way, since blockchains at their simplest are a form of data storage, we’ll need a way to extract out information to be able to use it. Web services bridge the gap for consumers to interact with data in the blockchain. Web services are also pervasive in how the world transmits and uses information nowadays. Even the video that you’re watching inside of this browser is thanks to a Web service, where the client is retrieving information that it needs from the server. Throughout this lesson, we’ll be breaking down this diagram. Learning how to modify our private blockchain with Node.js, RESTful APIs, and other third-party libraries to be useful for consumers to interact with. A lot of this lesson is about planning, planning, and more planning. In order to understand the thought processes behind this plans, they will help you in the future as you develop your own blockchain services and consider integrating them with Web services. In this lesson, we’ll guide you to understand, first, how to analyze blockchain use cases to determine if it requires a Web service. Then, decide on a Web service language. Next, we’ll explain Node.js frameworks and its components for the blockchain. Lastly, we’ll decide on an appropriate mock data set. Now, this course assumes that you already have some familiarity with the concept of Web services and are comfortable using JavaScript. If not, please, do take some time to review the resources I’ve linked down below. Having a grasp of these topics will make your experience learning the upcoming topics much easier. Now, let’s start with an overview of Web services.

03. What Is A Web Service-XOQxJ66bESk.en

In the upcoming several sections, we’ll begin developing the ability to analyze your blocking use-case and determine if it requires a web service or not, whether that’s the backend, the frontend portion, or maybe both. We’ll begin by reviewing what is a web service, then discuss considerations with integrating a blockchain with web services. Lastly, we’ll plan how to configure web services with our private blockchain. So, we start. What is a web service? A web service is a function that can be accessed by other programs over the web, and don’t confuse a web service with a website. Websites allow people to communicate and collaborate with each other while web services allow programs to communicate and collaborate with each other. For example, you could go to the website google.com/maps and search for your home address to see a map of where you live in the browser. But what if you wanted to write a computer program that takes an address and shows a map similar to how Google map does it? You could either write a whole new mapping program from scratch or you could call the web service that Google map provides, send it the address and the service will return a map of the location, which you can display in your program. This is a very simplified example, but it illustrates that a web service allows programs to retrieve information from and submit information to some resource. Web services is split into the frontend and backend concerns. In client-server web service models, the frontend part is called the client, and the server side is called the backend. To help cement this concept in our minds, let’s check out this table comparing the frontend and the backend, focusing on the frontend side first. The frontend, or the client focuses on the presentation layer such as the graphical user interface or the command line. Common languages that developers use to create the frontend are markup or web languages such as HTML, CSS, and JavaScript. An example of a frontend is the Udacity classroom that you’re interacting with in this browser. A frontend developer created this user interface that retrieves information that you currently see. Things such as the video file, the text, and the images that are on the screen. The backend or the server focuses on the database layer or any other method of data storage. Common languages for backend development include NO-JS, PHP, Python, Oracle, MySQL and SAP, and these are all scripting languages. Remember what I said that the user interface of the Udacity classroom is a concern of the frontend or the backend part handles storing the data you’re able to see. For example, this video was stored in some database. When it needs to be displayed in your browser, the frontend talked to backend in order to retrieve and display that sorted video. Now, that wraps it up for a quick overview of what a web service is. With that in mind, let’s discuss what to consider when integrating a blockchain with web services.

04. Web Service With Blockchain Considerations-N9LEB9zYnT4.en

A blockchain can be thought of as a type of database, which means that we can plug it in as a server or the backend part of a Web service. Doing so allows the information to be consumable by a client application. Now, you might be wondering, does every blockchain need to interact with Web service? That’s what we’ll be discussing in this section. What to consider when deciding if your blockchain use case requires integrating with the Web service. So here are some considerations when deciding if your blockchain should or should not integrate with the Web service. First, if your’e in your use case, consumers require a user interface in order to interact with the application, then a Web service is needed. With a Web service, you can configure the application with the blockchain service to be consumable over the Internet. Let’s see an example of this. Say we have a blockchain that contains medical health records. This blockchain contains private patient data such as the patient’s name, their diagnosis, and their vitals. Saving data on the blockchain allows it to be securely encrypted and decrypted into a digest, so that only those with proper access such as health care providers can rightfully access it. Integrating the blockchain with a Web service allows our healthcare providers to securely retrieve, view, and edit this data. Some more things to consider if you have a Web service integrated with the blockchain, are whether or not every client needs to communicate with its own app instance. Also, is there a desire for no central server? This can be a safeguard if something were to happen to that central server. Well, in this case, using a web service integrated with a blockchain is likely to be a good choice. Alternatively, it’s important to remember that not every blockchain situation requires integrating with the Web service. Remember, certain tasks can be handled without using a Web service. For example, executing a contract can be done without using a Web service by just using a dedicated wallet or directly from the command line terminal. Also, if you’re building a mobile application that communicates with the blockchain platform directly, then there’s no need for a Web service. To recap, we discussed the considerations to think about when determining if a blockchain should or should not integrate with the web service. Remember that there are pros and cons to each decision. So, take the due diligence to research the implications doing so will have on your project when faced with this question. Now, can you think of at least one more reason a blockchain should and should not integrate with the Web service? I’d like you to take some time to think it over. Research some real life use cases online and then write about it in the following quiz. Doing so will better prepare you the next time that you’re presented with the blockchain and a Web service. Next up, let’s understand how the private blockchain that you built will integrate with the Web service.

05. Planning Web Services With Our Private Blockchain-L3wA8FRFiew.en

Currently, our private blockchain is isolated, but if we want the functionality to submit an audit data on it, we need to create a backend web service that allows us to consume and use the blockchain data. Now, this section is all about planning. Planning how to create a Web service with our private blockchain. For the upcoming project, you’ll create a Web service using RESTful APIs and other third party libraries that will interact with your private blockchain to submit and audit blockchain data and validate the blockchain health. Thus, transforming your private blockchain into a valuable Web service. Looking ahead, these are the steps that will take to accomplish this. First, we need to configure an API Web service with GET/POST endpoints. This requires building and deploying a local Web service with Node.js and configuring API endpoints with static mock data for testing. The endpoints will be able to get a block by its ID and then post information about a new block. Next, we’ll migrate your private blockchain to the API Web service. In doing so, we’ll also configure the API endpoints with your private blockchain. The endpoints will also be able to get a block by its ID and post information about a new block. It’s okay if you’re unclear about how to complete some or even all these steps just yet. We’ll be going over this altogether. Just understand that we’ll be moving through the process step by step in this manner, and I’ve also linked this plan down on the text below for your reference. Now, the past cubal sections was an overview of Web services and how it integrates with blockchains. We covered, what is a Web service as well as considerations when integrating a Web service with blockchains. We also looked at plans for building a Web service with our private blockchain. In the planning section, we lay out a guide of where we are and what needs to be accomplished. With this background, a plan of attack in mind, follow along in the next section as we begin to configure a Web service API, but first building and deploying a local Web service with Node.js.

06. Web Services With Node.js-iwe1A9UjDRk.en

This section is about planning and developing your mental tools. Let’s talk about how we made the decisions we did to configure an API web service with GET/POST endpoints. For this course and project, we decided to build and deploy a local web service with Node.js. I want to discuss the reasons behind why we chose to use Node.js and elaborate on its components there will be integral to the development process as we move forward. In this section, we will introduce Node.js then set it up and then quickly overview nodes components. Then, we’ll cover the client and server features and, lastly, discuss the appropriate mock data set remember a large part of this lesson is building the skills to know how to analyze your blockchain use case and determine if it requires a web service or not and if so, how to plan for it. With that in mind, let’s start with a quick introduction of Node.js.

07. Node.js Intro-q1X8ybR6twg.en

Let’s start with a quick introduction to Node.js and why we chose it to build our web service. Your private blockchain is coded in JavaScript. For the data in the blockchain to be consumable, we’ll add onto it Node.js components. Now before we decided on Node.js, we had to decide on a language. When working with a web service, there’s a number of different language options you can choose from, for example, Haskell, PHP, Python, Java, JavaScript, or Ruby. We chose to use JavaScript because, first, a very popular developer language. Many of you watching probably already know JavaScript. So, you can quickly jump into developing without needing to take extra time to learn language. Also, there’s a wealth of existing tooling already available, which, as a developer, is really nice. This means you don’t have to reinvent the wheel every time from scratch. Knowing JavaScript and Node.js are enough to build programs that interact with many major blockchain APIs, including Bitcoin, Ethereum, and NEO. Lastly, though seemingly simple, JavaScript is a really expressive and powerful language, hence why it’s gained so much popularity in the web development world. Now, these are the reasons we use. When building out your own web service and trying to decide what language to use, keep these considerations in mind. Are you concerned with the front-end, the back-end, or both components? How well is this language maintained? How well does this language integrate with other systems? What is its performance like? Keeping these thoughts in mind will help you narrow down your choices to the best option. Once we decided JavaScript is our language of choice, we needed to decide which JavaScript tool to use. In the end, we chose to use the JavaScript engine, Node.js. Node is a very popular open-source runtime environment that executes JavaScript code server side. Unlike other JavaScript development, it requires running in a web browser. Node.js provides a runtime environment directly on the computer. Node.js is built on Google Chrome’s V8 VM engine, which in turn supports JavaScript in the Chrome browser. It runs on various platforms such as Windows, Linux, Unix, and Mac. In addition to this flexibility, we focused on Node for this project because Node uses single-threaded, non-blocking asynchronous programming, which means that it’s very memory efficient. It’s adopted by many enterprise companies, including Walmart, PayPal, and Uber, meaning, it’s very scalable. As a flourishing open-source community, constantly creating new modules, leading to a large ecosystem of open-source libraries. Lastly, it allows the use of the same JavaScript code for both front-end and back-end development, leading to a cleaner codebase. Now that we’ve decided to use Node.js to build our web service, let’s set it up on our computer.

09. Node.js Components-h1SXRwrL0A8.en

Node.js has a number of components you’ll need to be familiar with. If you are already comfortable with Node, feel free to skip over this section. However, if you would like to brush up on your Node knowledge, stick around. Your private blockchain is coded in JavaScript. So, we’ll be adding onto it Node.js components for the data in the blockchain to be consumable. The Node platform offers us a lot of components to help us built this out. Now, we won’t go into detail about all of them, only focusing on critical components that we’ll be interacting with in this project. Let’s start with the general concept of modules. Related pieces of code are encapsulated into modules and they can be thought of as JavaScript Libraries. Node has different types of modules. First off, there’s a core modules. Now, these are the bare minimum Node.js functionalities provided to you by the platform. These include the HTTP module, which includes classes, methods, and events to create a Node.js HTTP server. There’s also the FS module, which helps you work with file input and output. There are also third-party modules, which are a wrapper for some API functions for third party companies. For example, there’s mongodb module, and this is a wrapper to easily interact with mongodb. Then, we have the package.json file. Package.json is a file the lives in the root of your package/application. It tells NPM how your package is structured and how to install it. This is similar to a manifest in other applications. Now, speaking of NPM or Node Package Manager, this is a package manager for Node.js packages or modules. For the project, you’ll be using it to configure and manage project dependencies. Lastly, we have the Node Version Manager or NVM. This is a tool that allows you to seamlessly switch between different versions of Node. You can install each version with a single command and set a default via the command line interface. For the project, you’ll be using it to compare Node versions and make a selection based on the project needs. Instructions for installing NVM are linked down below. There are wraps of the core components of Node that we’ll be discussing. Next, we’ll take a look at the client and server features, and how we can use them to configure API endpoints to retrieve and post block data.

12. Mock Data Set-tvj_2RSGPDs.en

Let’s wrap up this discussion with the topic of mock data for a web service. In this section, we’ll cover why use mock data and choosing an initial data set. So first up, why use mock data. Before deploying live and during your development process, it’s important to routinely test your project for bugs as you’re building it out. If you wait until the very end to start testing, it’ll be much harder to figure out the causes of issues that come up. Testing with mock data also allows developers to simulate that their code works as desired without affecting any live production data. When integrating your blockchain with web services, there are many considerations for choosing to test with mock data. Here are some things to keep in mind. Block size. What happens if the amount of new data going into the block exceeds the maximum block size? How will this be handled? Chain size. If there’s no limit here, it’s important to test block creation functionality and performance as the chain continues to lengthen. Performance. How long does it take to query if it requires looking at every single block in the chain? Security. Are there weaknesses that allow the data to be easily hacked? Data corruption. What happens to the data in a block if a block gets corrupted? Is there a way to repair the block and can the chain beyond the damaged block be reached? Remember, whatever your reason for mock data, to test early and to test often. Next, let’s see the considerations when choosing an initial mock data set. First, know what type of data you’re going to work with ahead of time. This saves you a ton of work down the road. For example, if you start coding for a string, then you find out you needed an integer. This means you need to go back and revisit those functions to support this datatype. When it comes to web backend services, configuring backend endpoints requires understanding what responses are expected for client requests. Knowing the desired outputs ahead of time, allow you to focus on particular endpoint solutions. This type of planning typically requires mock data. With mock data, you can utilize a string to mock the endpoint data as a placeholder with a desired output. Once the upload is concluded, you can remove the string and replace it with the real data. Using actual data can come in a variety of forms, from dynamic data held within a database to calling other functions or responses to a client requests. In our upcoming project, you’ll be using the blockchain that you built already as your mock data, and while this is a simplified use case, remember the purpose it serves. As the projects you build get more complex, these same considerations we discussed here will still apply.

14. Lesson Summary-94nOpbTvS2o.en

This lesson was all about planning and developing the mental framework for how to go about converting a private Blockchain into a valuable web services. In this lesson, we discuss how to analyze blockchain use cases to determine if it requires a web service. Then we decide on a web service language. Explained the Node.js framework and components for the blockchain. Lastly, decide an appropriate mock data set. Throughout this lesson, we laid the foundation for how to modify our private blockchain with Node.js, RESTful APIs, and other third-party libraries to interact with your private Blockchain to submit and audit Blockchain data. Coming up, we’ll begin the process to configure web API services with GET and POST endpoints.

img

Part 04-Module 01-Lesson 02_Web Services with Node.js

01. Lesson Overview-WnP_1VDp-08.en

Welcome to the lesson, Web Services with Node.js. This lesson is meant to help get you up and running with a few popular Node.js Frameworks. In the last lesson, we looked more closely at web applications and discussed the difference between back and front end development. We went over Node.js, which helps you serve both back and front end data. Knowing this helps you understand how to construct a solution for your application needs. In this lesson, we’ll dive deeper into how you can more easily build out applications using what’s known as a RESTful framework. RESTful frameworks give you access to guidelines and tools that help you develop applications more efficiently. Node.js has many frameworks, and in this lesson, we’ll cover three of them, Express, Sails and Hapi. We’ll cover when each framework could be the right tool for the job and when you might be better off with something else. You’ll also get up and running with the small Hello World application using each of these frameworks. Coming up next, we’ll look a little closer at what a framework is, then get started with our own application. So, welcome again to the lesson. I’m excited to get started with Node.js Frameworks.

02. BDND-C3L2-02.1 Framework Overview V4-p6KGXYwOiwM.en

Welcome back. Hopefully, you had some time to read through that blog post, to learn about a few of the frameworks available in Node.js. There’s a lot of options, but in this lesson, we’ll focus specifically on three of them: Express, Sails, and Hapi. Each of these are powerful frameworks with great documentation that are easily to get set up with. Before jumping into the code, let’s take a quick look at why they were built, and what problems they’re meant to help solve. First, let’s go over to expressjs.com. Here’s the homepage for this framework, that you can look to for everything from getting started to developer documentation. They pitched themselves as a fast, unopinionated, minimalist web framework for Node.js. Express was an early framework that helped lead to many other solutions. It was designed primarily as a middleware and routing framework. It’s common in Fullstack applications, two of which are the MEAN, and MERN stacks, where the E stands for Express. Learning Express is extremely valuable, and will both help you develop applications as well as understand many of the concepts related to other Node.js frameworks. One of these frameworks that stem from Express is Sails. Sails is a real-time MVC framework for Node.js. You can get to their website by going to sailsjs.com. Here, you’ll see they’re Get Started section, and can scroll down a little to see more about what they’re hoping to solve. They make it easy to build custom enterprise-ready Node.js apps. It was built to help teams build scalable Node.js projects for startup and enterprise customers. We’ll be coming back to this site soon,, but first I wanted to go over and give you a quick intro to the Hapi framework as well. We can go to their website at Hapijs.com. Their pitch is that Hapi is a rich framework for building applications and services. Hapi was built by Walmart to solve problems they were having trying to manage their applications using Express. Trying to manage the codebase wasn’t scaling well, and Hapi has tried to design a more scalable solution. So, that wraps up a very quick intro to these three frameworks. Before moving on, feel free to look around through these sites, and try installing them, or getting started. This installation and getting started is also what we’re going to be going over in the next few sections. So, if you want to try it on your own, that’s great. But if not, then you can follow along throughout the rest of the lesson. When you’re ready, I’ll see you in the next section where we’ll start working more closely with Express.

02. RESTful Frameworks-3VpiWpMpaYY.en

Hey, and welcome to this section on RESTful frameworks. When starting to build web applications, you’ll quickly notice there’s a lot to learn. Creating everything from scratch can take a ton of time. Luckily, there’s ways to avoid doing everything from scratch using what’s known as a RESTful framework. RESTful frameworks help facilitate quick creation of robust applications by using things like code guidelines or libraries. In this section, we’ll define what exactly a web framework is, when you would use one, and quickly introduce a few frameworks that are available for Node.js. So, let’s get started. To understand what a RESTful framework is, let’s breakdown the term a bit. First, REST stands for Representational State Transfer. It’s a set of rules that defines guidelines based on the HTTP protocol. By following these rules, applications can know what to expect from each other, and it allows them to interact and integrate more easily. Frameworks that follow these rules are considered RESTful. So, we know what RESTful is, but what about frameworks? A framework is a set of tools and guidelines designed to support the development of web applications. Basically, with a RESTful framework, you’re following guidelines made to create applications that are based on the rules of the web. These rules and guidelines are just meant to make it, so that in the end, we can quickly create applications that can be easily managed. There’s a few reasons you might want to use a framework. First of all, there’s nothing in a framework that you couldn’t technically do yourself. It’s just a knowledge base of code and information built to help you work more effectively. With that in mind, it’s easy to understand why you might want to use one. Frameworks help you build rapidly using out-of-the-box functionality. They give you access to code that’s been built and tested by a community of developers. They also help extend functionality of your code to integrate with even more tools and frameworks. Before getting started with frameworks, it helps to consider a few things. Different frameworks have been made to solve their own unique problems in their own unique ways. This makes it important to understand what you’re trying to accomplish, as well as how framework might be able to help. Sails, Express, Hapi, and others are all frameworks that are available to you in Node.js. A lot of these are covered in a great blog post that I linked down below the video. Throughout the lesson, we’ll focus specifically on these three frameworks. Coming up, we’ll give a basic comparison between them, how to get started, and then you’ll build a basic application with each of them. So, take some time to read the post. When you’re ready, I’ll see you in the next section, where we start to highlight the features of Express

03. Express.Js Code Walkthrough-Y575BVGM7Ig.en

Welcome back. At this point, we have our first Express application up and running. Looking back at the code, we can try to understand what just happened here. To see the code, open up your project files in whichever editor you use. In this video, we’ll walk through each line of code to explain how this app works. Start by going to your index.js file. This first line sets a constant name “Express” that requires the express package. To see what’s going on in the next line, it helps to go back to the documentation. Under Guide, Writing middleware, you’ll see that they broke this line down for you. Here’s what it’s doing. On the variable app, it’s calling the Get method. It’s looking down a certain path here, then passing in a request and a response. This request-response is similar to what you learned about the client-server relationship from earlier. The client makes a request, and the server sends a response. Same thing here. As you can see, that’s exactly what we’re doing in our code. Here’s the path, the request, and the response. One thing you’ll notice, is that our code look a little different than what’s on the site. It uses something known as an arrow function. This is a newer syntax in JavaScript that’s meant to replace the curly braces. This helps us put everything in one line, rather than spreading it across multiple lines. We could put them back in like on the website, and it would work exactly the same way. This last piece here is sending “Hello World!” to our application. Next, here’s what the last line is doing. It’s giving us a place to see the application, and telling us that it has done that successfully. This part here is what we read in the terminal when we first ran the application. This first part of the line opens up port 3,000 and lets us view it from there. This is why we can view the application on localhost 3,000 using our browser. So, that’s basically everything that’s going on here. It’s a small amount of code, but grasping the concepts, connecting the pieces, and feeling comfortable with what’s going on is important at this point. If anything feels unclear, you can always continue working through the documentation or playing around with the code to see how things changed. It could also help to experiment with more examples. So, feel free two continue through the Express.js Resources to work through the guides they’ve created. If you’ve followed along, then great job building your first Express application. If not, then hopefully you have some time to try and get this started for yourself.

03. Express.Js Getting Started-rs7tvfjszdA.en

Hey, and welcome to this introduction to Express js. In this video, we’ll start taking a deeper look at the Express js Framework. We’ve already gone over a little about what it is and what it helps with. So, in this section, we’ll mostly focus on getting you connected to the resources you’ll need to get started. To start, head back to expressjs.com. Like we saw before, they pitched themselves as a fast, unopinionated, minimalist web framework for Node.js. To break this down a bit, opinionated would mean that the framework has strict guidelines or best practices that you’re meant to follow. Unopinionated means that you have more flexibility to operate outside of these types of guidelines. Minimalist describes that the code has been written concisely and efficiently. This video to the right gives a great overview of the history, purpose, and goals of the framework. Watching this video is a great way to learn a few extra details about Express. Next, it shows you how to install Express. You can do this using npm install express. All this command is saying is Node Package Manager, install Express and save it to my package.json file as a dependency for my project. We’ll be doing this soon when you build your own project. Down at the bottom of the page, it goes over a few of the main features of Express. It helps easily create APIs, provide some web application features, and has been used as the foundation for many other frameworks. Finally, to view Express resources and documentation, the top menu bar is a great place to start. Here, you’ll see documentation like getting started, guides, API references, advanced topics, and other resources. We’ll be working through some of this documentation throughout the rest of this section. Before we do this, check out the text below to help get things organized and when you’re ready, we’ll start working through this and creating our “Hello World” application with Express.

03. Express.Js Hello World-9acoSLSygQ8.en

Hey, and welcome back. Hopefully, you had a second to prepare for this video. Here, we’ll get started creating your first Hello World Express application. Back on expressjs.com, go to Getting Started, Installing, and you’ll see details about how to install this on your computer. To avoid just talking through all the documentation, I thought it might help to immediately put this to use. Let’s do that now and install Express to create our first project. If you get lost, remember that I’m just following this documentation here. I didn’t want to walk through it. In case you get stuck, this video might be able to help you get past a couple of the problems you have. To start, open your terminal and navigate to wherever you want your project to be. I’ll put mine on my Desktop. Now, make a folder using mkdir. Call this folder whatever you like. I’ll stick with myapp. There it is. Now, navigate into the folder from the terminal using cd My App. Once in the folder, use npm init to create a package.json file. What comes up here is a bunch of things you can assign in the file. You can always change this later if you want, and it’s fine to accept the defaults for now. To accept the default, just keep hitting enter a bunch of times until you’ve gotten through all the prompts. The last thing it does is ask, “Is this okay?” Right above that, it shows you everything it’s about to put in the file. Hit enter one more time and you just created your package.json file. Let’s check it out. Great, just like I expected. Next, I’ll create the JavaScript file that we’ll use for our hello world example. Using touch, I can create this file. I’ll call it index.js. Finally, I’ll type npm install express —save. This installs Express and saves it as a dependency into the package.json file we just created. After a few seconds, the framework will install and we’re ready to open up our project. To do that, I’ll open up the folder in my code editor. Over on the left, you’ll see all the files we just created. Index.js, package.json and a folder which contains all the modules that Express installed. There’s a lot of functionality here. We won’t go over all of them now, but if you’re interested in learning more, you can do that back on the website resources. Under Resources Middleware, you’ll see all these modules with links to more information to explore. For now, what we’ll do instead is try the Hello World example. To get there, go back to getting started and click Hello World. Take this code and paste it directly into your index.js file. Now, save this file. We can run this now to get our application started and afterwards, I’ll describe a little bit about what’s going on. To run this file, go back to your terminal and type node index.js or whatever you named your JavaScript file. Now, it should say, “Example app listening on port 3000,” which is great. That means we can check this out on the browser now to see our Hello World application. To do that, open your browser and type localhost:3000. If it says Hello World, then you’re all set and you just created your first Express web application. If you got this far, congratulations! We’ll take another quick break here. I put an overview of the steps we just went through down below the video. Once you’re ready, come see the next video where I’ll walk through a bit about what the code is actually doing.

05. Hapi.Js Environment -exXbhCW2EDQ.en

Hey and welcome back. At this point you’re hopefully up and running with your Hello World Hapi JS application. In this video, we’ll open up the project we just made to get a better idea of what’s going on with the code. To start, open up the project folder in your editor. What you’ll notice here is that there’s much less going on than there was with your Sales JS application. It actually looks much more similar to the Express application. Here’s the node modules, the package.json and the server.js file we created. The server.js file is a little different than what we saw in our Express application’s index.js file, but it’s doing all the same basic things. Let’s walk through some of the code to get a better idea of what’s going on here. First, we create a constant that requires Hapi. In the next few lines, we create a server hosted on port 8,000, which is why we’re able to access this app at localhost 8,000 in the browser. Next, we add the roots in, in this case using GET, but can be GET or Post or whatever, depending on how you want to handle the URL endpoints. This is followed by the path for the URL. In this case, it’s being placed at localhost:8000/hello. Down towards the bottom, you have the functions that are used to start the server. Some error handling and a lock to the console that tells you the server is running. So, that’s really the basics of what’s going on inside the project folder of your Hapi JS application. We went through this a little quicker than the other applications because it’s a lot of pretty similar stuff that you’ve seen already. As always, you can check out the documentation and resources supplied on the Hapi JS homepage. This is a great way to learn more about this framework’s functionality, or to keep going through some of the tutorials they provide. Great job working through this section and congratulations on getting started with your Hello World Hapi JS application.

05. Hapi.Js Getting Started -o-O5ZSCdjlA.en

Welcome to this video, on getting started with hapi js. In this video, we’ll quickly go over the goals of this framework as well as the tools and resources available to you as a developer. To get to the hapi js website, go to hapijs.com. As we’ve seen they pitch themselves as a rich framework for building applications and services. They’re selling point is that it allows developers to focus on writing reusable application logic instead of spending time building infrastructure. This makes it super quick and simple to get started building applications and it’s a great fit for the project we’ll be working on in this course. Right on the front page they show you how to install this framework using npm install hapi, which we’ll be doing in just a minute. Scrolling down a bit they go right in and show you how to start building an application for yourself. You will initialize with your package.json saving hapi.js as a dependency, and below that is the script we’ll use to start up and run your application. Back up at the top of the page, you’ll get access to documents, resources, tutorials and a community of developers that can help you out along the way. Looking over at the resources, you can see the books that they recommend to get started. Books are great, but sometimes it take a lot of commitment to get through, especially if your main focus isn’t on mastering hapi js. In that case, you can go down a little further and see different resources like code samples, boilerplates, projects, tutorials, and videos. These are excellent ways to get more ideas for what you can accomplish using hapi js. Finally, head over to tutorials to help get started with installing and creating your Hello World application. We’ll be working through this next, but since we’ve been through a few of these now, you might feel comfortable trying it for yourself. If so that’s great, but if you’d rather walk along with me, then we’ll be going through it in the next video and I’ll see you there.

05. Hapi.Js Hello World-3p2kgUpM2Bc.en

Hey and welcome back. In this video, we’ll walk through the steps needed to create your hapi js Hello World application. To get started, go back to hapijs.com and click on Tutorials. The first tutorial is to help get you up and running with hapi js. To start, we’ll need to create a directory for our project. To do this, open your terminal. I’ll create mine on my desktop. So, first I’ll cd to my desktop, and then make a directory called hapi-app. Next, cd into this folder and type npm init to initialize npm for the project. After initializing npm, type npm install hapi —save, to install hapi js and write dependencies to your package.json file. After this, you’ll create the server script in Sails js. This was done for you, but we did something similar to this, when we were getting started with Express. To create this file, I’ll use touch server.js in my terminal. Now that we have all our files ready, we’ll need to paste the server script code into our server.js file. For this, I actually prefer to use the code shown on the homepage. It’s slightly different than that on the tutorial page, but I find that it’s quicker for me to get started this way. So, I’ll go back to the homepage, paste in the code and save this file. Perfect. Now, we have everything set up and we’re ready to run our application. To run the file, open your terminal and type in npm start, then hit Enter. This creates an application you can view in your browser by going to your local host. So, let’s go to the browser. Go to local host:colon8000/hello and there we go. We’re up and running with our hello world application using hapi js.

07. Sail.Js Environment-tn2WboXLiMI.en

Hey and welcome back. Now, that we have a sales JS application, it helps to look at the files and folders that are making it all work. As you probably noticed, sales JS has provided a lot more functionality out-of-the-box then expressed it. The upside of this is that you can get started quickly with your application. A possible downside is that it could be more difficult to get familiar with everything that’s going on to make the application work. In this video, we’ll walk through the main features of our new application. To start, open your environment using your code editor. What I see here first is the.gitignore file. This file explains itself pretty well. If you haven’t seen one before, take a minute to read through it. Basically, it gives you a way to exclude files from your apps repository if you’re using Git. Since so much has been installed for you to get started, sales JS made an excellent ReadMe file to help you understand all the features they provide. The package.json file is where all the dependencies for the project had been saved. Similar to, in your express application, this holds various metadata about the project and helps npm manage the projects dependencies. In the node modules folder, you’ll see all the modules that were installed. You can find the details about what these modules do using the documentation. You can also open up the files and look through the code yourself, if you’re interested to see how any of the functions are working. To create this application, we originally run sales lift in our terminal. To see how to run this without sales list, you can go to the app.js file. Its goals, purpose and documentation are described right here in the file. Basically, this is saying that you can start the application using node app.js, just like how in Express, we run node index.js. If you’re interested in seeing the files that create each of the pages generated by the application, you can find them under views. For each of these, you can go back to the application and see things like the emails, layouts, account, dashboard, and more. This is all functionality that was provided automatically when you selected one while creating the application from the terminal. If you don’t want this in your app and would prefer to start from scratch, you can always create a new application without this default functionality. To do that, just install sales like before, but select two rather than one during the installation process. So, that’s the basics of how this application is working behind the scenes. Like I mentioned, it’s quicker to get started this way, but can be a little trickier to get used to where everything is. If you’re familiar with folder structures from other web applications, this hopefully isn’t too much different than what you’ve experienced already. If you have any questions about getting started, sales JS provides many tutorials and resources to help you along the way.

07. Sail.Js Hello World-n6Dy9mMLxAI.en

Welcome back. In this video, we’re going to walk through creating the Sails “Hello, World!” application. We’ll just be following along through their documentation. So, if you’d rather speak through and do it yourself, you’ll be right along with us by the end of this video. If you stick with us, hopefully, there’s some helpful tips and tricks along the way that will help you get even more familiar with the process. To start, head back to sailsjs.com. Once you’re there, click on Get started. Scrolling down, you’ll see the directions on how to start building your application. At this point, you’ve hopefully been working with Node.js for awhile already. So, you can skip this first section. Now, jump over to your terminal to install Sails using the command they show, npm install sails -g. After a few seconds, you’ll have Sails installed on your computer. Next, we need to create a place to hold the test project. To do that, I’ll go to my desktop, create a Sails project folder, then cd into that folder. Now, type sails new test-project. A prompt will appear that is giving you the option to either start your app with existing functionality or to start from scratch. For this demo, we’ll start with the template web app by selecting one. At this point, all the dependencies will start to install, which can take a minute or so. You can open the folder to see all the files that are being installed. When it’s done, it’ll let you know that the Sails app test project was created. Finally, navigate into your test project folder using cd test-project. Then type sails lift into the terminal. See, it’s not only the squid pictures in documentation, even the code itself is playing off the sailboat analogy. At this point, you’ve lifted the Sails, and you’re ready to check out your Sails application. Open a new browser window and type localhost:1337 to see how it looks. It’s pretty nice how much they set up for us to start. The page itself directs you through what they’ve done, how it works, and where to find even more resources. Feel free to look around for a little while to explore your new application. When you’re ready, come back to us the next video, where we’ll go through the project files to look through what just happened.

07. Sails.Js Overview -tDoi7JAhRuM.en

Hey, and welcome to this introduction to Sails js. In this video, we’ll start taking a deeper look at the Sails js framework. To start, we’ll go to sailsjs.com. The first thing you’ll notice here is the cool-looking squid that links to some basic information. This squid is the start of a trend you’ll see a lot with this framework. It seems like they’ve done everything they can to make connections between the framework, and sailboats, and ocean creatures. You can scroll down a little to see the main things they point out that Sails can help you with. The framework is written completely in JavaScript, can connect to any database, and provides blueprints to help create Rest APIs instead of building them from scratch. Also, it’s compatible with any front-end like Angular, React, iOS and anything else. It’s got easy WebSocket integration and also provides professional support for its users. What this all means is that it’s simple to use, well integrated with other tools, and has excellent documentation to help you get started. You can see all that up here in the menu bar. Under get started, they help you set sail with the basics of starting your first application. From installation, to app creation, to some new cool ideas, it’s all here to help support you along the way. Under support, you’ll see community resources like FAQs, live chat, Stack Overflow, and classes you can take. There’s also professional resources like partnerships, support, presentations, and Sails job opportunity. Finally, under the documentation, you’ll find stuff like reference material, descriptions of important concepts, tutorials, and even more useful resources. They’ve made this site really intuitive for you to explore yourself. So, feel free to read through and work through some of the material they provide. Coming up, we’ll work through their Hello World application together to help make sure you’re comfortable with the basics. So, if you’d, like explore documentation for a bit and when you’re ready, we’ll see you in the next video.

img

Part 04-Module 01-Lesson 03_Utilizing Third-Party Libraries

01. Lesson Overview-sSeMfPka4Ew.en

Welcome to the party. The third-party library, or I’ll see myself out. So far in the course, we went through the planning stages of integrating your private blockchain to a web service, and then dove into the Node.js Framework. This here is a quick lesson, where we’ll take a look at some common libraries associated with these frameworks, which we’ll be using in the upcoming project and discuss the ever growing importance of handling security on a blockchain web service. These are the lesson topics: how to discover and use common third-party libraries, using Bitcoin Core as an example to discover third-party libraries to assist with RPC functions that we’ve seen before, and lastly, discuss the risks and precautions of working with third-party libraries and wallets, or anything that stores value. All right. With that, let’s get cracking.

02. Third-Party Libraries With Bitcoin Core-2Ym6UOrw7xk.en

In this video, we’ll discuss common third-party libraries that you can use to support your blockchain development needs, and then round it out by discussing considerations when choosing a third-party library. As developers, we know that using third-party libraries carries several benefits. First, we don’t need to recreate code. Also, it allows us to take advantage of vetted code, and it makes our code cleaner. You learn how to take advantage of RESTful frameworks to use HTTP to obtain data. Now, what about other third-parties to help us interface with other aspects of the blockchain platform? To interact with external services, there are a few options to configure our codebase tool set. The first option is to create our own functions and organize these functions into a library that can be accessed with our codebase. The second option is to use a proven third-party library. The second option is more attractive as it saves development time, and often, increase the security. Of course, this will depend on the age of the third-party library along with its community support. Let’s use our past experience with Bitcoin Core and discover solution to interact with the Bitcoin RPC functions utilizing our RESTful framework in Node. Remember that RPC stands for remote procedure calls, which describes the system when you send a command to a remote system, where it’s processed and the results are returned back. An example of an RPC function that you used before in Bitcoin Core’s debug console is verifymessage. This function takes in an address, a signature, and a message, and returns back true or false, whether or not the signatures verified. To reiterate, what we want to do is find a NodeJS third-party library that will allow us to interact with Bitcoin Core’s RPC function. There have been a number of third-party libraries created to wrapped RPC interface. If we just open up Google, and do a simple search for NodeJS Bitcoin Core, the first we always see is Bitcoin Core Node package. This package or library can interface with RPC, execute wallet operations, and query the network in the blockchain, which is everything that we’re looking for. If we scroll down that page a little bit, we see that GitHub repo, how to install it using npm as well as how to include it using require Bitcoin Core. Even further down on that page, you’ll see a state that all RPC methods are exposed to the client interface as a CamelCase version of those available in Bitcoind. Knowing that, here’s a code snippet of what are verified message RPC method that we’ve seen before in the debug console would look like as a function in Node. I’ve included this code snippet down below. Notice here is a CamelCase version of what we use in Bitcoin Core. It also takes in the same parameters, an address, a signature, and a message, and returns back true or false whether or not that signature is verified. We won’t get into the implementation mechanics in this section just yet. I’m showing you this to demonstrate how we can find third-party libraries that support your blockchain Web Service needs. Later in this course, you’ll get a chance to implement out similar features on your own private blockchain. Now, we just saw one common third-party library, specifically for Bitcoin. There are many other ones for other platforms such as ethereumjs-util. As the overview page states, it’s a collection of utility functions for Ethereum. It can be used in NodeJS or it can be used in the browser with browserify. It’s also a pretty active package with over 3,000 weekly downloads. I’d like you to take some time to think of two more blockchain platforms that you find interesting, and search for some popular third-party libraries you could use when developing for them. You might be surprised at the community of developers already at work building out tools for these platforms. One last thing to call when choosing a library, do a security check. What I mean by this is look into how often it is updated. You don’t want to pick a library that’s older and neglected in a newer framework. Doing so, you run the risk that if there are problems with the code, it likely won’t get fixed, and you either need to do unwanted workarounds, or have to scratch your efforts, and start all over again. Here’s a recap of what we covered. We discussed some common third-party libraries for Node, and explored a simple use case of how to use one for Bitcoin Core to wrap RPC functionality. We ended by discussing considerations when choosing a library. Like I mentioned before, take some time to think up two more blockchain platforms you find interesting, and search for some popular third-party libraries you could use for developing with them. Not only will this help you sharpen your skills to discover useful, healthy and well-maintained third-party libraries, it could save you some time down the road if you ever do want to develop for these platforms.

03. Security - Third-Party Libraries And MultiSig-XsyrPzEU8qc.en

Third-party libraries bring a lot of benefits, but there are security concerns, especially when dealing with wallets or anything that stores value. We’ll wrap up this lesson by discussing some of the best practices of working with third-party libraries and wallets and talk about using multisignature wallets as a security solution. Have you seen working with RESTful frameworks and third-party library integrations, such as bitcoin core npm? Third-party libraries make development a lot easier, but they can also introduce risks into your project. Here are some best practices to keep in mind to help minimize these risks. Use well-tested libraries. Well-tested libraries come from reputable sources with the advantage of being tested for many different scenarios. Many enterprise companies create libraries for their own benefit, but then release them to the public. Since these companies have an incentive to make sure the code doesn’t negatively affect their own systems, we as outside developers can benefit from their vetted code. Thoroughly examine the documentation. To know how to effectively use a third-party library, you must read the documentation. Proper documentation will help you learn about usage restrictions, data input and output, and other important implementation details. Focus on scalable libraries. Like we saw with hapi.js, which is used for large businesses like Walmart, choosing a scalable library means you won’t have to rewrite the code if your project grows beyond the limits of the third-party integration. Lastly, check security. This can’t be said enough. Working as a blockchain developer, you’ll often be dealing with confidential, high-value data. With the rise of data theft and hacking, pay close attention to security features of the library. What data security and encryption does it provide? You don’t want to risk introducing your project to security vulnerabilities. This goes hand in hand with thoroughly reading the documentation. On the topic of security, I want to mention multisignature wallets. Multisignature wallets require more than one key to authorize the transaction. Let’s use bitcoin as an example that we’re most familiar with. Here, standard transactions require only one signature from the owner of the private key, associated with the bitcoin address. However, bitcoin networks support much more complicated transactions. They require the signatures of multiple people before the funds can be transferred. These are often referred to as m-of-n transactions. The idea here is that there are multiple parties involved in order for anything to get done. These parties can be people, institutions, or program scripts. Multisignature scripts set a condition where there are n number of public keys, at least m of them must provide signatures for the transaction to go through. This is a m-of-n schema, where n is the total number of keys, and m is a threshold of signatures required for validation. Depending on the network, there may be a limit set to the number of n public keys. Here are some real-world example use cases. In a one of two schema, say there’s a husband and wife joint bank account. The signature of either spouse is sufficient to spend the funds. Smart contracts on Tumblebit, Coinswap, and Lightning Network can have a two of two schema. Meaning both parties must sign in for the contract to execute. Here’s a notable example in practice. Bitfinex, one of the world’s largest cryptocurrency exchanges uses a cold storage wallet. Now, this is a wallet that is kept offline. This is a three of six multisignature wallet. This wallet as of December 2017, contain over 141,000 bitcoins, and that’s valued at over $1.5 billion. Presumably, the keys are kept very, very safe by Bitfinex’s operators. A number of companies have developed multisignature wallets, from Armory, to Coinbase, to Electrum that we’ve worked with before. In future development, you might find yourself working on a platform that requires the security of a multisignature wallet, requiring multiple parties to present a valid signature before the data can be accessed. We won’t be covering how to implement this now. But, do keep this in mind in the future as a way to increase the security of accessing data on your blockchain back room service. To wrap this section up, our topic of focus was security. We discussed some of the best practices when it comes to using a third-party library, and ended on the security offered by multisignature wallets. Security will be a major concern on almost every blockchain platform you end up building on. So, be vigilant when leveraging existing code and scoping out the safest route for interfacing with your blockchain.

04. Lesson Summary-78Rcj1PLsqk.en

Now that was a short but really important discussion, and let’s recap what we covered. We used Bitcoin Core as an example to discover third-party libraries, such as bitcoin-core and ethereumjs-util. We discussed the risks and precautions of working with third-party libraries and wallets. Lastly, we explored multi-signature wallets that use an M-of-N transaction scheme. Now, what’s next? Moving forward, you’ll pull together all the steps as you configure an API web service with GET and POST endpoints, and migrate over your private blockchain.

Part 04-Module 01-Lesson 04_RESTful Web API with Node.js Framework

img

Part 04-Module 02-Lesson 01_Digital Assets with Blockchain Identity

01. Lesson Overview-fHTsmi77bPU.en

Hey, and welcome to the lesson. In this lesson, we’ll extend beyond some of the basic ideas of web services we went over previously. We’ll help you build some extra functionality into your private blockchain that helps you work with digital assets. You’ll learn to encode and decode these assets, which will allow you to post them as data and a new block on the blockchain. But why would you want to do this? Well, first, our blockchain is currently limited to storing basic values to help validate transactions. But using these same core concepts with just some added functionality, we can extend this idea of validating ownership to digital assets like png, jpeg, mp3s, and more. To get there we’ll start by learning a few new concepts like what exactly a digital asset is, what encoding and decoding are, and then you’ll get some practice doing this for yourself in Node.js. On top of learning these new ideas, our goal is to help prepare you to complete the next project. There, you’ll extend the functionality of your private blockchain to include the ability to notarize digital documents for yourself. For more details, you can read through some of the text we’ve placed down below the video, and when you’re ready, we’ll see you in the next section.

02. Digital Assets-gqy4xEntqT8.en

Welcome to this section on Digital Assets. To develop this in future lessons, we’ll start to work a lot with digital assets. Before getting started, we wanted to help define what these actually are, and why they’re important to the blockchain. Understanding how digital assets work on the blockchain will allow you to create an entirely new set of applications whose scope goes far beyond simple transactions. From movies and Music, to business and legal documentation, there’s a lot to get excited about in this space. With that in mind, let’s look a bit more into Digital Asset. First, a digital asset can be a lot of things. But overall, we consider it to be both digitally stored content or an online account owned by an individual. These are valuable because it allows us to take things like books, songs, or videos and access them online, rather than needing to create them physically. This is something most of us deal with every day, so it’s not too surprising. Something I was interested by, is that accounts are actually considered digital assets too. In this case, something like a bank account, a subscription, or a membership could be considered a digital asset. So, digital assets are common, but what’s not is common, is understanding exactly what they are, and how we can work with them programmatically. You’ll probably recognize files like GIF, JPEG, and MP3. There’s many other types of digital assets ranging across topics shown here, like images, video, 3D files, and many more. To help us transmit these files online, they’re usually compressed and optimized. A compression algorithm is any algorithm made specifically to achieve a very fast transmission rate, or a small amount of storage space. These algorithms are used on digital assets to help us store, send, and load assets as we work with them. But, even with these compression algorithms, the blockchain isn’t really the best place to store these files. While it’s possible, it can be pretty slow and expensive because as we’ve seen, the blockchain as a database suffers from issues with the cost and speed of storage. What the blockchain can do very well, is help improve the way we manage the ownership of these digital assets. This is something that has been a struggle in the past for many industries, and is where the blockchain really shines. Even with licensing and copyrights, Digital assets traditionally have issues with theft, payments, and royalties associated with the ownership of digital rights. The blockchain handles this issue in the same way it handles transactions. The difference is, instead of saying, “Who owns this transaction?” we’re asking, “Who owns this asset?” It’s a simple concept and theory, but extremely helpful in practice. Coming up, we’ll add on a few new ideas to what you already know, to help get you set up to manage the ownership of digital assets using your own private blockchain. So, that’s it. We looked at what a digital asset is, went over a few examples, and have a basic idea of how digital assets were on the blockchain. Coming up, we’ll start our journey into digital assets by reviewing the basics of encoding, decoding, and starting to work with them for ourselves.

03. Encode And Decode Data - Part 1-WVqO1tJPhlg.en

Now that we know what a digital asset is and how it’s related to the blockchain, it’s important to step back and consider some important questions. How do digital assets work? To get the answer, we can look at a more specific question. That question is how do computers understand the contents of a file, and how do they present those files to people? Once we understand how this communication happens, we’ll be ready to start incorporating these ideas into our blockchain applications. Here, we’ll specifically focus on one answer to this question and it has to do with encoding and decoding. Encoding and decoding is the process of producing and interpreting information. It’s used across many fields of study. But in computer science, its main focus is facilitating the sending and receiving of data. It’s the process of translating a message between human-readable data and raw data. We encode information into raw data to allow computers to send information in a format they understand. Later, this information is decoded into a format that people can understand and work with. Next, let’s look a little more specifically at encoding. Encoding is the process of putting a sequence of characters like text into a specialized format for efficient transmission or storage. What’s special about this is what it allows you to do. Basically, the goal of encoding is to help us send and receive messages between each other. For example, when speaking to another person, if you both know the same language, you can just speak freely and understand each other. Now, if instead of talking in person, you put that message into a computer, you’re not just talking to that person anymore. You’re including computers in the conversation. For that reason, they need to understand what you’re talking about to send messages. This is done using encoding. There’s a couple ways to encode data, some of which you may have already heard before, things like hexadecimal, Base64 and ASCII. We’ll cover each of these in more detail soon. The point to keep in mind for now is that each of these encoding schemes can take in information to encode it as raw data. This raw data is what is then transmitted between computers. One thing to note here is that you might remember the algorithms used to generate private keys like SHA-256. These algorithms are used for encryption, which is different than encoding. With encryption, you’re trying to make a secret key in a way that can’t be reversed and only you have access to. With encoding, you’re simply trying to reformat something to make it easier to transmit. Another thing to note is that encoding isn’t really the same as compression either. The goal of compression is to make file smaller. With encoding, you actually can end up with a larger file, but the important thing is that the speed at which it can be read and transmitted is improved. The steps on how to encode data are different depending on how you would like to encode it. We’ll be encoding images using these ideas later in the lesson, but first, let’s look a little closer at decoding. While encoding prepares files for efficient transmission or storage, decoding does the exact opposite. Decoding allows you to take encoded, raw, unreadable files, and convert them back into a human-readable format. You’ll decode something anytime you want to present information to someone in a way that they can understand and work with. Using the same schemes like hexadecimal, Base64, and ASCII, you can convert the raw data files back into the file type they started as. The process of encoding and decoding is happening constantly. When you upload a file to a website, you’ve encoded data that will be decoded when someone needs to use it. If you’ve ever used a service like Skype or Google Hangouts, you’re receiving a live stream of data that was encoded, transferred over the Internet, and decoded to present to you. The end result is that the computers and networks get to communicate in a format they use, and you get to communicate using live video or whatever media you happen to be using. So, that wraps up our basic overview of encoding versus decoding. The idea here was just to clarify what these terms mean and their purpose. Coming up, we’ll look more specifically at certain types of encoding.

03. Encode and Decode Data - Part 2-5Qgnm3ZlHuI.en

Now, that we have some idea of the purpose of encoding, it’s helpful to review a few ways to encode that are commonly used. In this video, we’ll look into the basics of three common ways to encode data: ASCII, hexadecimal, and Base64. Different types of encoding are used for different purposes, and there are a few important details to review about each type of encoding. We won’t be going into a lot of depth here. All we need is the basic understanding of how these types of encoding work. If you’re interested in learning more about these, we’ve put a lot of links to resources below that you can follow and learn more. First, let’s look at ASCII. ASCII is short for the American Standard Code for Information Interchange. It’s based on the idea that you can represent text as numbers. Here’s an ASCII table. As you can see on the chart, by laying out a series of characters and letters, you can now reference the corresponding number associated with its character. For example, P is equal to 112, Q is 113, and so on. It maps the text we write into numbers that computers recognize using binary to transmit information. To check this out for yourself, you can head over to any basic online ASCII converter. This and other encoding schemes have tools available online that you can experiment with. Over on unit-conversion.info, we can do a quick demo showing an example of converting text to ASCII. Here if I type in P, we get 112 just like we mentioned. Q gives us 113 and you’ll notice that even the space has its own number shown here as 32. This extends to anything we want to type like blockchain developer, your name, or an entire book. These same basic ideas are what’s used for all encoding including Hexadecimal, which we’ll look at next. Hexadecimal encoding is pretty common. It’s a more concise and human-readable representation of binary often used by programmers. Something encoded in Hexadecimal will be represented using numbers from zero to nine or letters from A to F. Here’s a chart showing the basic conversion between binary and Hexadecimal. When encoding a document, these values are translated into their Hexadecimal equivalent. It’s more common to work directly with Hexadecimal when using assembly languages. It’s a way for developers to allocate memory more quickly than specifying space using binary digits. If you’re interested, you can head over to the website convertstring.com to try converting data to Hexadecimal for yourself. Type your text in the top, click Hex Encode and check out the encoding down here at the bottom. Over at blockchain developer again to see how this looks. If you take the time to break this down, you’ll see that it follows the zero to nine, A to F format that was shown in the chart earlier. Finally, Base64 is another encoding scheme meant to represent data as numbers in a string format. It does this by converting information into any one of 64 different characters shown on this chart. So as you can see, A equals zero, B equals one and so on through both upper and lowercase letters along with a few characters. Using this chart, you can convert any text you’d like into its Base64 equivalent. Like before, we can check out a website to see this for ourselves. Over at base64encode.org, you can demo converting text into Base64. Similar to before, I’ll type in blockchain developer, hit encode and then I can check out the Base64 encoded version of this text. So, there’s a quick overview of a few different encoding schemes; ASCII, Hexadecimal, and Base64. There’s a few other types of encoding out there. They all serve the main function of converting our human-readable media into computer-readable formats that can be more easily transmitted. For us, it’s important that we recognize these different formats, so we can begin to work with them for ourselves. There’s plenty of resources to understand each of these in more depth and I linked a few of my favorites down below the video. Feel free to check these out to better understand each of these encodings and play around with some of them for yourself.

04. Encode and Decode Data Demonstration-hsf5h10Arro.en

Hey and welcome back. Hopefully, you had some time to check out some of the resources about each of the different encoding schemes. In this video, we just wanted to go over a quick demonstration of how to encode a file to hexadecimal to show you how easy it is. To do this yourself, you’ll need to open up a terminal Window and cd into whichever directory you like. I’ll use my desktop. First, let’s convert back and forth between a string we type directly into the terminal. To do this, type, xxd dash p Blockchain Developer. What you’ll get back is a hex encoded string that represents this text, there it is. Now, if we want we can convert this back into its original string. To do that, we type echo, paste the hex encoded string you got, then the command, xxd -r -p. What we get back is the original string, “Blockchain Developer”. All right, you’ve already encoded and decoded your first message. The command xxd is a Linux command that allows you to make a hex dumped or do the reverse. If you’re not totally sure what that means, it’s what we just did. A hex dump just provides the hex encoding for any value, and the reverse is decoding it back into its original form. Doing this in the Terminal is great, but what if we want to get this information in the files? Well, that’s simple too. In that case, you just need to provide the file names, we can do that now. First, create a file using, touch hello.txt. Open that file and type in whatever you like. I’ll type, Blockchain Developer. Now, go back to your terminal and type the command, xxd -p, followed by the file you want to convert, and the new filename. For me, that’s hello.txt and helloEncoded.txt. This creates the encoded file for you to view if you’d like. Now that you have that, let’s decode it. To do this, we’ll use -r to reverse the hex dump. We’ll follow this again with the original file and the file you’d like to create, that looks like this. I’ll call my final file, helloDecoded.txt. After running this, we can see that we’re back in the original text file. You can look at the file to see that is the same string that you had before. Finally, let’s try this with an image. To get started, I’ll go search for an image and bring it into my desktop. I’ll get a cat picture for now, and rename it to something simple, cat.png. Next, open your terminal then use the same command as before. Type, xxd -p, followed by the name of your file, and follow that with the name of the file you want the hex to be dumped to. Running this encodes this image file as hexadecimal. If you open it, you’ll see that it’s a lot longer than the text dump was. Now, let’s decode this back into its original image. Type, xxd -p -r, followed by the name of your file, followed by the name of the file you want for your new PNG. Now, we’re back to our original image. Pretty cool. All right, so that’s it. It’s pretty quick and simple, but it’s interesting to see that you can begin working with these encodings for yourself. We placed a couple of files down below the video with a problem set you can use to try encoding and decoding.

06. Poex.io Demo-U5kmGRDVP1I.en

In this video, we’ll demonstrate how proof of existence works in practice to help you verify digital assets. To help demonstrate this, we’ll use a service that goes by the same name, Proof of Existence, also known as POEX. This online notarization service is built on the Bitcoin blockchain. If we navigate to this site, there’s a link to a demonstration. Let’s check it out to see how the process works. The first step is to submit the digital asset you want notarized. Once you do, POEX creates a unique identifier linked to the time which the document was submitted. The digital asset is hashed using sha256. The next step is that in order for this unique identifier to be recorded, POEX needs to create a new transaction. Step three is validation. Once the transaction is created, the unique identifier that was created is stored in the blockchain. Even if this site no longer exists, evidence of the document will always be there and it could be found from a Bitcoin blockchain explorer. Let’s take a look at these confirmed document digests. How about this one here? This is the sha256 generated from the digital asset. Remember this number. We’re navigated to this page with the transaction ID info. Grab the transaction ID and take a look at it in the blockchain info block explorer. Next, check out the output scripts. Notice the return opcode. To mark this transaction as unspendable, POEX marks the OP_RETURN operation code. Also, it appended a unique identifier in front of your documents hash. This unique identifier converts the phrase DOCPROOF into ASCII. To search for verified documents, we can use OP_RETURN to narrow it down. Some online services like Coin Secrets or blockchain.infoslist can help you locate OP_RETURN transactions more easily. To sum it up, these are the steps this specific service uses to validate digital assets; first a digital asset is hashed using sha256. Next, that hash is appended to an identifier. After that, the hash plus the identifier is put into a generated transaction. Finally, the transaction is marked with OP_RETURN so it’s unspendable. The existence of that transaction in the blockchain proves that the document existed at the time the transaction got included into a block. So that wraps up this demonstration, hopefully, now you have a better idea of how POEX can help you validate digital assets

06. Proof of Existence Overview-_dr5Zf6vvxo.en

You’ve learned about digital assets and how to encode and decode that data to be stored on a blockchain. Now that you’ve seen how raw data is stored, how is it verified and why is that important? To verify the integrity of these digital assets, we’ll need to check for ourselves. This means we want to confirm that it contains the correct sequence of bytes and that it has not been wrongfully accessed or altered. Keep in mind here that integrity is only about making sure that a given file is exactly the same as it was at its source. It doesn’t refer to the trustworthiness of that source, only that the file was not changed. In order to verify digital assets, we’ll need to understand the concept of proof of existence. There’s a couple different ways we could prove a digital document exists. Two of them that we’ll see in more detail are SHA256, and MD5. Proof of existence is used to publicly proof and authenticate any digital asset on the blockchain. It does this by verifying its hash. One thing that might be surprising is that it’s not a form of consensus like proof of work that we talked about before. Think of it as a blockchain notary service. In a traditional notary, we need to take a document to an authorized person who notarizes or signs and stamps it. When they do this, they claim they verified the document. Similarly, proof of existence verifies the authenticity of documents on a blockchain. Here’s how it works at a high level. Usually, when information about a digital asset is stored on the blockchain, only its hash is saved. The document itself is not stored on the blockchain. This way, the private contents of the digital asset did not need to be publicly revealed. The hash is linked to the time the document was submitted. This way, you can later confirm the data existed at this time and verify it. So, there’s the basic ideas behind proof of existence and how it can help verify digital assets. Coming up, we’ll look a little further into these ideas and explore how they work in practice.

07. Securing Assets Using Your Digital Identity-LYtxxrroQvc.en

So far, we learned how to encode and decode digital assets into raw data. We also discussed the importance of Proof of Existence to verify the ownership and existence of these digital documents. You saw how one online service conducts proof of existence, but that’s not the only method. For the upcoming project, you’ll build your own version of a Proof of Existence notary service using your private blockchain. This will allow you to secure an asset with your digital identity, a Bitcoin wallet address. To get started, we’ll review a few important topics: securing assets with a digital identity and ownership of digital assets. To secure an asset means to protect these resources from wrongful access or alteration. So, why even secure an asset? Well, assets are useful to us whether directly or indirectly. For example, a banana is directly useful because we can eat it. A legal document is indirectly useful because we can use it to claim ownership over something. In this case, maybe your document claims you own the entire banana farm. Digital assets work similarly. As we’ve seen, we can use Proof of Existence to verify its ownership. The next big question is how do we prove who owns a digital document? For example, say I take a picture with my phone that I really like and save it to a blockchain application. To prove that I own the photo, it is encoded into a data object and that object can contain multiple properties. If we encoded that photo as a hash and submitted it on the blockchain, we could save the information as a data object with these properties. First, type equals jpeg; next, the Bitcoin wallet address of the user that secured this asset on the blockchain. Along with that, we’ll store the time that digital asset was embedded on the blockchain, and finally, the hash of the previous block this current block is tied to. In this case, the user has used their digital identity to secure the digital asset by embedding their information in the same block. In the future, the existence of that information together in the blockchain proves that this document existed at the time the transaction got included into a block. This is the basic idea behind how Proof of Existence works at a lower level by allowing users to embed their identity along with the hash. The identity is used to secure the digital asset. This allows whoever owns the blockchain identity to claim ownership of the asset in the future. These ideas of securing assets with a digital identity provides the foundation of what will allow us to build a notary service using Proof of Existence. Hopefully, now you have a better idea of what it means to secure assets with a digital identity. Coming up, we’ll zoom out a bit to look at how digital asset management fits into the evolution of blockchain from Bitcoin to ethereum.

08. Blockchain Generations-7RmRVq9RdeE.en

Until now, we’ve mostly focused on understanding the blockchain fundamentals using Bitcoin. You may have noticed the word Ethereum sneaking in more often throughout this lesson. That’s because coming up, we’ll start to apply a lot of what we know to Ethereum, an entirely new blockchain platform. Before getting started, we wanted to step back and mention why we even started learning on the Bitcoin blockchain. We did this because Bitcoin is often considered the first generation of blockchain. Things like transactions and many of the core concepts you learned were first developed and implemented on this platform. The great thing is that many of these ideas were adopted by future generations of blockchain. Soon, we’ll move on to the second generation of blockchain which introduce something known as smart contracts. This idea of smart contracts led by Ethereum opened up many new opportunities to work with digital assets on the blockchain. But like we mentioned, there are a ton of similarities between a Bitcoin blockchain and the Ethereum blockchain. In this section, we’ll give a high-level overview of how digital asset management fits into the overall scheme of these different blockchain generations. Bitcoin, and simple alternative coins like Litecoin and Monero, are part of the first generation of blockchain also known as blockchain 1.0. These blockchains focus on moving value, maintaining a ledger, and creating ideal payment systems. Blockchain 2.0 build on the concept of recording transactions on the blockchain. To do this, they added in the ability to program and use logic associated with this data. This code is used to create what we refer to as smart contracts. Ethereum led the way on this idea but they are quickly joined by others like Ethereum Classic, NEO and Quantum. Smart contracts on these platforms allow for customizable transactions. Engineers can use this functionality to fit the needs of whoever is dealing with these transactions. They can help exchange money, property, shares, or anything of value. Similar to other blockchains, they try to do this in a transparent, conflict-free way while avoiding the need for third parties. You can think of smart contracts as a legal contract that runs on code. An event like an expiration date triggers the contract to execute whatever code is held in it. The addition of smart contracts allow developers to create projects on top of the blockchain platforms, as well as launch blockchain-based businesses and organize decentralized governance. These contract-based applications also give businesses the potential to automate many tasks and processes that would otherwise be impossible. It’s even allowing us to build entirely new types of applications known as decentralized apps. Even though they’re considered different generations of blockchain, they share a few important similarities. This is where identity comes in. For one, both Bitcoin and Ethereum depend on wallet addresses to function as identification for transactions and services. They’re also both a public record of transactions that have taken place. They both allow users to autonomously interact with information on the blockchain while allowing others to verify your data. Recall on the first project, you created your own blockchain identity. This identity was an encrypted, private-public key pair from a Bitcoin wallet, and was used to securely authenticate your identity for transactions you posted in the first project. Even this is extremely similar between Bitcoin and Ethereum. Moving forward, we’ll segway into the Ethereum platform where these same principles apply. The main difference is instead of managing transactions, we’re managing digital assets. For example, here’s an image of an Ethereum wallet. You may have not seen this before but you might be already recognizing some similarities between this and your Bitcoin wallet. For example, you can see here that the user’s account is tied to a key. So, that wraps up this overview of the different blockchain generations. It’s important to notice the connection of what we’re building now and how it connects to other platforms and projects you’ll be working on. As the space continues to grow, these basic ideas will stay pretty similar. We’ll always have amazing new tools as the blockchain continues to grow, but staying focused on these core ideas will help you learn these platforms more easily.

09. Lesson Recap-XT7buWXBCR8.en

Congratulations, you’ve reached the end of this lesson. Throughout this lesson, we worked with encoding and decoding digital assets. After that, we moved on to a proof of existence and touched on the basics of different block chain generations. The goal is to help you implement this type of functionality on your private block chain. This allows you to start posting assets as data into a new block in the block chain. It also helps you manage assets like images, videos, audio files, and other digital assets in the same way you’ve been able to manage transactions with your web service. This lesson was also meant to help prepare you for the next project. We will be adding some functionality to your web service. We’ve put a quick review of what was covered down below the video. Take some time to review these ideas and when you’re ready, move on to the project to get started.

img

Part 04-Module 02-Lesson 02_Build a Private Blockchain Notary Service

img

Part 05-Module 01-Lesson 01_NEW Introduction to Ethereum

01. Lesson Introduction-J2ulDHMGXxE.en

Hi, and welcome to the lesson. In this lesson, we’ll go over the basics of Ethereum. I’m PK, and I’ll be your instructor for this and the next few lessons. You haven’t seen much of me yet, but Brandy, Elena, and I had been behind the scenes building the projects you have been completing throughout the program. As well as working with Udacity, I’ve funded to blockchain startups. At my most recent startup, LINCD, we specialize in blockchain strategy and distributed ledger infrastructure. Our focus is helping companies understand how do blockchain enable their business. On a daily basis, I work on a variety of blockchain technologies, including Ethereum and I will bring that hands-on knowledge to teach you how to get started for yourself. Throughout the lesson, you’ll hear from me, and also learn some new concepts from Joe. An instructor you’re probably familiar with from earlier in the program. Earlier, you learned how the Bitcoin blockchain works. Throughout this course, we’ll use these ideas to introduce the Ethereum blockchain. You get up and running with Ethereum’s tools, developer ecosystem, and protocol. Ethereum is a completely separate blockchain platform from what we’ve gone over so far. We’ll start off by introducing its purpose, along with some basic terminology. By the end of this lesson, you’ll start using some of these tools for yourself. The goal is to make sure you’re prepared to develop more complex applications using Ethereum. You’ll also get to know the supply side of Eata, the various consensus algorithms available to us, current performance of the Ethereum network, scaling plans, and also understand topics such as accounts, transactions, gas, fees, network types, and the Ethereum, which we’ll mention itself. I am really excited to teach you these topics, and can’t wait to show you a Ethereum through a dev lens.

02. Blockchain Framework Refresher-B4bYtFQnTyM.en

Before getting into Ethereum, we wanted to give you a quick refresher on the block chain framework. This was covered in earlier lessons, when we spoke about Bitcoin, and we’ll also anchor us as we progress through the Ethereum world. As you’ll see, there are many similarities between these two block chains, and a lot of your previous knowledge, will be directly applicable as we explore the theorem. Here’s a quick recap on the list of components from the block chain framework. In this video, we’ll walk through the framework, to make sure you are familiar with each of these steps, and how they relate to one another. First, transactions. These are the basic atomic units of work, submitted by a user to a node, to be included in the next block. Next, the wallet, which contains a wallet address. The wallet address is like an email address that you share with others, should you want them to send you crypto-currencies like Bitcoin, Ethereum, and many more. Users send transactions to one another using Wallet addresses. Before the network validates a transaction, it needs a signature. A signature is the process by which one signs the transactions before submitting to the node, for inclusion into the next block. After signing, the transactions enter the Mempool. This is where all unconfirmed transactions are placed, until mining nodes validate these transactions. All transactions in the Mempool are waiting to be picked up by a node in the network. This network is distributed in nature, where everyone is able to download a copy of the ledger, to their local computer. This makes it so, that there’s no centralized ownership of information, and allows the network to determine which transactions are valid, and which are not. The network achieves consensus by determining which transactions are valid. Consensus is the name for a group of algorithms that can be used to create a voting mechanism, or process for a given block chain network. We’ve gone over some of these algorithms earlier; like proof of Work, proof of Stake, but there are many more. Once the network agrees, transaction is placed in a block and hash is assigned. Hashing is a process of generating a digital fingerprint, also known as hash, by passing data or information to a hashing function. This helped us identify a block, and know whether or not the information has been tampered with. If information has been changed, the hash will also change, which invalidates the block. A block is a container that holds a list of transactions to be added to the block chain. Finally, these blocks are linked together using hash values, into what we call the block chain. This block chain is a shared ledger where the blocks are chained together. It contains the entire history of transactions that have been made on the block chain. This allows us to easily see which transactions are valid and not. So, there’s a couple of components we went over before in the block chain framework. Moving forward, we’ll see that all of this is very similar in a theorem. That said, there are some important differences. Coming up, we’ll go over some new terminologies to better understand what these differences are. This will help us as we transition into building our own Ethereum based applications.

02. Ethereum Basic Terminology-wlcTQk_IFJA.en

Now that you are refreshed on the blockchain framework, let’s enter the Ethereum world. We’ll use this section to cover some basic Ethereum terminology. First, Ethereum is an open source, programmable public blockchain platform. It includes its own scripting language known as Solidity, and has an entirely separate ecosystem of tools from what we’ve learned before. These next terms I will go over are a huge part of what makes up this ecosystem. It’s important to understand the Etheruem Virtual Machine also known as EVM. The EVM is capable of executing logic, algorithm, and process data inputs. Unlike its predecessors, Bitcoin, where a user is given a set of predefined operations. In a Ethereum world, a user is able to create their own operations. These operations can vary in complexity, which by design gives room for creating several decentralized applications, including cryptocurrencies and tokens which we’ll cover later in this course. Next, one thing that really separates Ethereum from Bitcoin is that it’s Turing Complete. Turing Complete is a term given to any software that is able to run code written by a dev or executed by an end user. In a Ethereum, a developer can write an application using a programming language call Solidity that is modeled after languages such as Python, JavaScript, and submited to an EVM for execution. In Bitcoin, there are limited ways to write applications, only to store information. As a developer, you’ll use this to write what is known as a smart contract. In fact, you’ll be using this language very soon in this course and for the upcoming project. A smart contract is basically a contract written in code. In a Ethereum, these are written to programmatically enforce rules set up in a negotiation between two parties. More specifically, a smart contract is also known as an object on the Ethereum blockchain that contains EVM code functions. Amongst many other things, a smart contract can store data, make decisions, interact with other contracts, and send data, the currency of Ethereum. These smart contracts will exist and be executable so long as the network exists. Just like other blockchain technologies, there is no one that owns this contract and no one can take it down, not even you. A smart contract will only disappear if it’s programmed to self-destruct with a kill switch. For this reason, having a kill switch is a good practice when working with smart contracts. As we mentioned, smart contracts are written in adherence programming language which is known as Solidity. This is a high level language for coding and deploying smart contracts. It is not exactly like any other language, but its creation was heavily influenced by C++, Python, and JavaScript. Solidity has a few features similar to these other languages. It is statically typed, it supports inheritance and libraries, and has complex user defined types. Finally, all this leads towards one major goal of Ethereum, which is for Ethereum to become a world computer. Ethereum aims to implement a digital computer that is decentralized globally, and executes peer-to-peer transactions and contracts. The blockchain platform and public network together is termed as the general-purpose world computer. Ethereum isn’t the only blocking attempting to do this but it was the first and it’s still leading the way. For that reason, we’ll be focusing on Ethereum as a platform. We’ll use this to write our own smart contracts using Solidity, and we’ll create applications that become part of this world computer.

03. Ethereum Virtual Machine-8zCytjpjyeU.en

Before wrapping up this overview of new terms, let’s recap an important part of ethereum known as the Ethereum Virtual Machine or EVM. The EVM is the machine that powers and runs the ethereum platform. It’s often called the operating system of ethereum. It’s what’s responsible for running the thousands of nodes spread across the world. To do this, all nodes on the ethereum network run the EVM as well as validating transactions. This worldwide distributed set of nodes running the EVM is what we refer to as the world computer. Almost everything we learned about ethereum so far is possible because of the EVM. The state of ethereum blockchain is what allows us to understand things like the account balance of each user, and it’s the EVM that helps manage this. The accounts we mentioned like EOAs and CAs are connected to the EVM. Also, every transaction that gets initiated goes through the EVM. Even the gas it cost to run computations is calculated by the work done on the Ethereum Virtual Machine. As the name suggests, an Ethereum Virtual Machine is a virtual machine that executes code. Said differently, it’s a runtime environment for smart contracts. In an implementation layer, it uses a stack-based architecture. There are several implementations of this already live on the main network. These are go-ethereum, Parity, cpp-ethereum, Py-EVM, and others. These are what allow us to access the EVM’s functionality using different programming languages like Go, C++, Python, and others. In this program, we’ll be using go-ethereum. You’ll learn a little more about how to get started with go- ethereum a little later. To start, Geth is a go line implementation of the ethereum protocol. It is the most common implementation used to interact with the ethereum network. We think that makes it a great place to start. But let’s get back to the EVM. On top of everything else we mentioned, it’s also what allows you to run a node to build and deploy smart contracts. Once a smart contract is written, it is compiled into two views. A bytecode view that is machine-readable, and an assembly view, which is human-readable. Then this compiled code executes on the EVM, which executes the logic of your program. As well as operating the main network, there’s also an isolated portion of the EVM used for testing. This testing ground is important for smart contracts that need to verify their quality before going on to the main network. You’ll be using this part of the EVM to test your code when you start building smart contracts. So, that’s what the EVM is, and why it’s such an important part of ethereum. It really is the heart of ethereum, and is responsible for a huge part of what allows us to build functional applications on the ethereum network.

03. Ethereum Vs Bitcoin-y3NmPR-sdgo.en

As you’ve seen, there are many similarities and differences between Bitcoin and Ethereum. At this point, it’s helpful to compare them to get a better idea of how each of these platforms operate. In this video, we’ll walk through a table, comparing and contrasting Bitcoin with Ethereum, across a few of their core attributes. We’ll look at things like, permissions, scalability, currencies, and more. Let’s get started. First, both Bitcoin and Ethereum have permissionless restrictions. That means that anyone who wants to validate transactions and create blocks, can do this, there’s no restrictions on becoming a part of either of these networks. This is different from a permission system. In a permission system, notes would need permission from a central authority to join the network. Networks achieve consensus in each of these platforms, using the Proof of Work algorithm. Ethereum is currently working on migrating to Proof of Stake, with a project known as Casper. We’ll highlight this more later, but for now, they’re both using Proof of Work. Next, the scalability of these platforms are similar. Because of this, they share both upsides and downsides with each other. Allowing anyone to join the network is great for scaling the user base and expanding quickly. That said, both platforms struggle to scale performance. Figuring out how to do this is a huge discussion taking place in both communities. For comparison, Bitcoin takes about 10 minutes to settle a transaction, and Ethereum takes about 15 seconds. That might seem like a huge improvement, but let’s compare that to Visa and MasterCard. These process about 5,000 transactions per second. With that in mind, you can see there’s still a lot of room for improvement. Next, let’s look at the regulation of the protocol. By this, we mean the way decisions get made within the community. Bitcoin and Ethereum both have improvement proposal systems in place. Because of this, they’re able to work with both an open source community, as well as a core set of developers, to contribute to its developing ecosystem. This means, there’s a huge opportunity for you to get involved in these platforms to help them improve. Both of these platforms are pseudoanonymous, this means that their identities are tied to their public keys. So, while transactions are still anonymous, they’re not completely anonymous. It’s possible to see who made a transaction, if you can trace the user to their public key. Each of these platforms also have a native currency, Bitcoin and Ether. This isn’t always the case with other platforms. In some cases, a platform won’t have any currency, or they could have a token, that’s dependent on a platform like Ethereum, to operate. Finally, the potential for scripting is different between each of these platforms. This is the main focus of these lessons, so we won’t go into too much detail here. The languages provided by Ethereum, like Solidity, are the basis for smart contracts that we’ll be developing. While Bitcoin does have some scripting functionality, it’s not as capable as Ethereum in the sense. All right. So that finishes up this side-by-side comparison of these platforms. As you can see, they’re actually more similar than they are different. Some of the main differences are their scripting, currencies, and in the future of their consensus algorithms. Keep this in mind as you continue to learn more about Ethereum. Working through these new tools and ecosystems can get pretty complicated. Being able to relate this new information to ideas you already know, will give you a great start as you continue learning.

03. Why Ethereum-Mm4Hmy-nszI.en

Throughout this lesson, we’ll work through many new ideas related to the Ethereum protocol. Before jumping into these ideas, it’s helpful to understand why Ethereum exists at all. In this section, we’ll answer a few important questions about Ethereum. What are its goals? Why was it even created in the first place? We’ll compare Ethereum to earlier protocols, and discuss how it tries to improve on them. To start, here’s how Ethereum defines themselves on Ethereumm.org. They’re ”A decentralized platform that runs smart contracts: applications that run exactly as programmed without any possibility of downtime, censorship, fraud, or third-party interference.” With that in mind, let’s look at why they chose to become this type of platform. Earlier blockchain protocols functions similar to a machine. Like bikes, toasters, and cars. They’re created to serve one single purpose. In Bitcoin, we saw that they solved for currency. Other early blockchain protocols serve for single issues in a similar way. The next set of blockchain protocols decided to become more flexible. This allows them to adapt to a few possible applications instead of focusing on one. These protocols were more like a Swiss army knife. If you need a new functionality, these protocols could adapt to allow it. This allowed the protocol to change based on the needs of their users. The problem with these protocols is that the upgrades take a lot of work from developers. I like to think of this type of protocol as functioning like Legos. Every time someone wants a new feature, you need to go and add in a new piece. Over time, this can add up and you end up with a huge tower that’s difficult to manage. More specific to blockchains, these protocols often have a variety of transaction types. This is great. But if you want new functionality, engineers need to add new transaction types. In this case, the protocol keeps growing to fit the needs of users at the expense of becoming very complex. This is where Ethereum comes in. Ethereum set out to solve problems it solve with these earlier protocols. The goal it had in mind, was to create a generalized platform that allowed others to develop on top of it. This lets users define their own needs and develop apps that solve for their unique problems. By using this approach, Ethereum allows us to use the same ideas you already know about blockchains, and extend them even further. You can go beyond basic functions without Ethereum needing to update its protocol. This solution is more like an operating system than a Swiss army knife. Operating systems give you the tools to build many applications on top of it, and that’s what Ethereum is set out to do. To do this, Ethereum has a programming language named solidity. We’ll be working with solidity later to build applications on the Ethereum platform. In our case, we’ll be making an app that allows you to register stars on the block chain. In other cases, you might want to create a supply chain management system, or even a game for collectible kittens like you’ll see later. In each of these cases, the Ethereum protocol is what allows us to build on top of this platform. For that reason, we’ll continue to explore this protocol and the tools you can use to work with it throughout the rest of this lesson. That wraps up the bit of the history that led to Ethereum. Hopefully, this helps you better understand where it came from, and the unique solution it provides to developers.

03. World State-jZ2EmFYNSUU.en

Over the next few sections, we’ll walk through some terms that are new and some that might be familiar already. We’ll take some time to walk through how each of them relates to the Ethereum protocol. In this video, we’ll start that discussion by exploring the state of a blockchain. This term hasn’t come up much yet, so we’ll first define what we mean by state. From there, we’ll compare how state is handled in Bitcoin versus Ethereum. How a blockchain manages information within its data storage layer determines its state. It’s defined by variables, like how the protocol handles transactions, keys, fees and other information. In Bitcoin, unspent transaction outputs or UTXOs are what represent the state of the blockchain. You can use this state to figure out other information. For example, you can use the sum of these UTXOs to find the number of Bitcoins owned by a user. What’s interesting in Bitcoin is that it doesn’t have a way to represent an account balance. That information isn’t held anywhere. It’s found by referring to the state of the blockchain. But it isn’t an actual number you can find in the records. Instead, the account balance of a user is the sum of each UTXO owned by the users of a private key. That’s different from Ethereum in a few important ways. For one, the Ethereum state can manage much more than unspent transaction outputs. Ethereum can hold these account balances. On top of that, it holds a few other fields like the Nonce, Balance, Storage Hash, Code Hash, Account Storage and Ethereum Virtual Code. This state holds a list of all accounts and creates a mapping between an address and an account State. This might be a little vague right now. And that’s because it’s actually a brand new conceptual idea. Here’s what that means. Where in Bitcoin all information stays on the blockchain, Ethereum does this a little different. In Ethereum, the account state is separate. It is removed from the blockchain, but holds information about the state of the blockchain. The blockchain is still the ledger that maintains the history of transactions. This other information including accounts, addresses, and balances exists along with this state. Ethereum maps this information to the blockchain allowing it to track things like the account balance of user. This is possible because of something known as a Patricia tree. Trees are common data structures and you may be familiar with ones like binary trees or heaps. Patricia is an acronym. It stands for practical algorithm to retrieve information coded in alphanumeric. That’s a mouthful. And without diving too far into the details, the main benefit of this structure relates to storage. It allows Ethereum to store values in a way that expands the state to include the account values we mentioned earlier. That wraps up a quick overview of blockchain state and how it differs between Bitcoin and Ethereum. Coming up, we’ll look at how these states are determined by looking at account types on the Ethereum platform.

07. Network Types Funding Wallets Using Faucets-Fa-yr0PypPU.en

In this lesson, we’ll go over the various Ethereum network types, and how to connect to them using the MetaMask browser wallet. We’ll introduce you to some of the faucets where you can request for some play Ether for your wallet counts. Now, let’s install MetaMask. So, I’m at metamask.io, and I’ve attached this link in the resources section. So, you have two options; you can download this as a Chrome plugin, or a Brave browser plugin. So, I use Chrome and I use Brave as well. So, for this demo, we’ll just use Chrome. Yes. So, just click on this, go through the installation process, and you’ll have the MetaMask installed as a Chrome plugin. Now, once you have it installed, you can login into MetaMask. And this is one of the ways you can login. In here, if you click on the different networks that are available, you have the main network, and you have the various tests networks as well. Let’s go back. Main Ethereum, it uses Proof of Work, Ropsten uses Proof of Work as well, Kovan uses Proof of Authority, and Rinkeby uses Proof of Authority as well. So, for this illustration, we’ll use Rinkeby, and then I’ll just quickly show you how to request for some play money. So, if you’re using MetaMask, you can go to faucet.metamask.io, and you can request for ‘play ether’ here. So, once you’ve connected to one of the addresses, let’s say Rinkeby, you can just request here, and then it’ll show up in your MetaMask. So, you’ll have a transaction. So, I’ve requested before, so when you click on that link, it will show you in ropsten.etherscan when the transaction is successful. There’s other ways to request as well. So, if you went to, let’s say faucet.rinkeby.io, you can also request, it has three ways, you can essentially follow these instructions; Post a tweet or a Google plus or Facebook, and get the link and post it here, and you can get the play money given to you through the faucet. So, I’ve actually posted on Google Plus. So, this is basically my Ethereum address, I copy that link and I put it here, and then you can say, ‘give me Ether’. So, depending on what you want, you can get three Ethers every eight hours, 7.5 every day and then 18.75 every three days. So, I’m just going to go with this one, and it says, ‘Click on all those store fronts’. So, I think that looks like a store front, that one also looks like a storefront. Let’s see if it’s going to work. It’s thinking thinking thinking. So, while that’s going through, let’s just go through a quick transaction. So, I’ve got some play, Ether here. So, in the previous class, we went through the graphical user interface. Remember, we have four accounts, so, let’s say we want to send some play Ether from a MetaMask account to my graphical user interface. So, I’ll go here. Let me just get the address first. So, go to the first one, I’ll copy my address, then I’ll go to MetaMask and I’ll say, ‘send’, and over here, so let’s say I’m sending one Ether, and say ‘confirm’. You’re signing your transaction, and then within a few seconds, you should get, there you go. So, it went up to 6.5, it was 5.5 before we started the transaction. Yes. So, in conclusion, we went over the various Ethereum network types, and how to connect them using MetaMask, you browse a wallet plug-in. Now you know how to request for some play Ether for your faucets. This wraps up this section, we’ll see you in the next video.

10. Ethereum Accounts-Q2xtKYLlD7s.en

Accounts are a fundamental component of the Ethereum platform. These accounts represent an identity, used to make transactions by people, mining nodes or contracts. In this video, we’ll look at the basics of these different account types. We’ll also define each of the variables, that are used to determine the account state. In Ethereum, there are two types of accounts. Externally owned accounts, known as EOA’s, and contract accounts known as CA’s. Individuals holding a private key manage externally owned accounts. As a user on the Ethereum network, this is the type of account you would earn. There are few important fields associated with it. First, an EOA holds the account balance shown in Ether. It also includes a transaction count. This count is the number of transactions that originated from the account. An EOA, can do a few things. It can send transactions on the Ethereum network, call a smart contract, and transfer value from its wallet to another account. EOA’s are slightly different than contract accounts. Contract accounts, or CA’s, are accounts controlled by the code within a smart contract. On top of the account balance and transaction count, it also holds the smart contract code. In this case, the transaction count means something different than with EOA’s. In CA’s it refers to the number of times this contract has deployed other smart contracts. Like an EOA, a CA can also transfer value and initiate another smart contract. When receiving transactions, a CA can execute associated smart contracts, and in some cases, manipulate storage. These accounts can be created by another CA or an EOA. As we mentioned earlier, there are a few fields that determine the state of these accounts. These fields include the nonce, balance, storage hash, code hash, account storage and EVM code. Let’s look at each of these fields in a little more detail. First the nonce. The nonce refers to the number of transactions on the account. As we saw, this is slightly different depending on if it’s an EOA or a CA. In an EOA, this is the number of transactions sent from the accounts address. In a CA, it’s the number of contracts created by the account. The account balance is the total value of Ether available on the account. The balance is shown in Wei. A Wei is a smaller denomination of Ether. Like how penny is a smaller denomination of a dollar. One Ether, is equal to 10 to the 18th Wei. The storage hash, is the root node of the Patricia tree. The Patricia tree is the data structure that Ethereum uses. This tree stores the hash containing the contents of the account. Next, the code hash. Is the hash of the code within the smart contract. This code executes every time a call is made to the contract. While other fields can be changed, this hash cannot change. This is the reason that smart contract code cannot change after it’s deployed. In E0A’s, there’s no code. So, the code hash field is an empty string. That wraps up this overview of externally owned accounts, contract accounts, and each of their state variables. To summarize, EOA’s are tied to private keys, don’t hold code, maintain a balance of Ether, and consent transactions. CA’s, have code, a balance of Ether and can execute this code when triggered by transactions or messages. Coming up, we’ll look at the types of transactions and messages that exist. This will help us better understand, how transactions take place between EOA’s and CA’s.

13. Transactions and Messages-SiQPPoUfhTE.en

In a Ethereum, transactions move the state of the account. Their piece of instruction to submit to the blockchain generated by an externally owned account. In this video, we’ll go over different transaction types that exist on the Ethereum network, then, we’ll overview the transaction fields in each of these types. There are two transaction types; message calls and contract creation. Externally owned accounts initiate both message calls and contract creation. This transaction could be between a person and another person or a person to a contract. Here’s a diagram that shows each of these message types in a little more detail. On the left is a message call. This message call results in a change to the world state. This state change could be as simple as a change in Ethereum balance or a change in smart contract storage. To do this, the owner of an EOA signs the transaction with their private key prior to sending it on the network. After making this message call, it can trigger a message between EOAs and other EOAs, or EOAs and CAs. Contract creation is a little simpler. This also results in a change to the world state and is specifically used to create contracts. The type of transaction you create is determined by the values in each of the contract fields. Here’s an example of an Ethereum transaction. First, notice that there are a few fields like nonce, gasPrice and others. Let’s go over these fields in a little more detail. First, the nonce is a transaction count from the sender’s account. Every transaction that occurs needs to have a unique incrementing nonce. The first transaction you send from your account will have a nonce of zero, the second will have a nonce of one, and so on. Next, the gas price is the price the sender is willing to pay per unit of gas. We’ll be covering gas in a little more detail in the next section, but the gas price is a similar concept to [inaudible] and Bitcoin. Ethereum uses gas to determine the reward miners received for executing contracts, the price set here is the incentive miners have to mine new transactions. The gas limit specifies the maximum number of gas that the contract can spend. This is useful for a few reasons that we’ll go over it in a later section. Next, the To field is where you specify a recipient address. The amount of Ether you want to send is shown in the value field. This value is written in way. Finally, the data in Init fields are optional. But are what make Ethereum different from other platforms? Here, you can provide information used to record the creation and execution of smart contracts. This field is used when interacting with smart contracts. It will hold the code that lists conditions and consequences of the contract. That wraps up this brief introduction to transaction types and their fields. We’ll actually be using these fields soon when we start creating our own transactions.

14. Ethereum Gas and Fees-WoYQQi0I4Dk.en

When sending Ethereum transactions, you’re asking the network to execute code that sends ether to another account. Nodes execute this code in the network. Miners get paid fees using what’s known as gas. In this video, we’ll go over what gas is, how it’s related to ether and how it helps facilitate transactions. To start, keep in mind that the lifecycle of an Ethereum transaction is not much different than that of a Bitcoin transaction. In Bitcoin, there are Bitcoin transaction fees. In Ethereum that process is similar and uses gas. The reason this is similar is because both ethereum and bitcoin currently use the proof-of-work algorithm. When using this algorithm, the miners need this incentive to pick up the work. So, that’s simple enough. Ethereum pays gas to minors for executing code on the smart contracts you create. What gets sort of confusing is when you think why don’t we just use ether for that? Well, we actually do pay them in ether. This is where it’s important to understand the distinction between ether and gas. Gas accounts for the cost of executing the transactions in the first place. In your contract, every time you add, subtract, multiply or divide, that adds to the total amount of gas that the transaction will cost. It’s not the actual currency used for payments. Once the contract runs, the sum of these fees gets converted to its equal value in ether. Miners receive this ether which does have real-world value. As a quick analogy, you can think of this like how gas works in a car. Gas is important because it’s required for your car to function. The problem is you can’t actually go buy food with the gas from your car. You will need to convert this gas into money by selling it and then use this money to buy whatever else you want. That’s a bit strange, since no one really sells their cars gas, but it’s very similar to what happens in ethereum. In ethereum, gas accounts for the total cost of executing operations on the contract. Once completed, ethereum converts this gas into its value in ether and this ether goes to the node that executed the transaction. When you hear the word gas, people are usually referring to one of two things, the gas price or the gas limit. In the last section, you saw that both of these terms are included in the fields of a transaction. Now that we have a better idea of what gas is, we can go over these in a little more detail. First, the gas price is the price per unit of gas that you’re willing to pay for executing the code in your smart contract. This field is how you can incentivize workers to pick up your transaction. An important thing to note here is that the same amount of gas will be used regardless of what you’re willing to pay. What this price specifies is how much you’re willing to pay for each unit of gas. A low gas price will be cheap but it’s less likely that a miner would pick up this work. A high gas price is more likely to get picked up but can get very expensive if you want to execute this code many times. Finding a gas price that is both affordable and effective is a balance you’ll need to consider when determining the gas price. It’s not an exact relationship like shown here, but hopefully this graph helps get the point across. Gas limit is the maximum amount of gas a sender is willing to pay for a given transaction. Setting this limit is important for a few reasons. One, it allows you to work within a budget that you’re comfortable with. It also safeguards you from potential errors in the contract. For example, if there’s an infinite loop in your code, that’s bad enough already. With ethereum, you’ll also lose gas for each time this loop executes. This can add up pretty quickly, and by setting a limit you can ensure things stay within your budget. If you don’t include enough gas in the gas limit to execute the required code, you’ll get an error. In this case, you’ve both spent money for the gas and you don’t have the output you wanted. It’s sort of like filling the tank of your car halfway and then getting stranded on the highway. You didn’t get to where you wanted and you still wasted gas. However, it’s fine to specify a higher gas limit. In this case, the unused gas will be returned after the contract executes. So that wraps up this intro to how gas works in ethereum. For now, the important thing to understand is what gas is, when it’s used, and a few basic terms that we went over. Later on, you’ll build contracts that have these operations and run using gas. Using some helpful Developer Tools, you’ll be able to run tests and estimate the gas usage for your contracts.

15. Ethereum Network Performance-zx-kd-xgX3s.en

In this section, we will go over some topics related to the Ethereum network performance, and how to use a tool called Ethstats to look into some of the network metrics. First, it’s important to understand a few basic definitions and how they relate to the Ethereum network performance. To do this, we will be at this URL, ethstats.net, walking through a dashboard. If you’d like to follow along, I’ll have enclosed the link below the video. So, let’s begin exploring the dashboard from the top left hand corner. The numbers you see on your dashboard when you explore might be slightly different to what you hear in this recording. Best Block. It is the highest block number of the longest valid chains, said differently, it is heavy with current difficulty. Uncles or orphan blocks, and unlike other blockchains in ethereum, they are included and rewarded. The dashboard displays the current block uncle count, and that from the last 50 blocks. Last block is the time since the last mine block. It’s in seconds. Average block time is the average time between two blocks, excluding uncles. It should display something in 15 seconds. But right now it shows closer to zero seconds. Let’s browse to the right. Okay. Average network hash rate is the number of hashes spent by miners to find a new block. Typically, this is shown in tera hashes. So currently this particular dashboard is not synched, so it’s probably showing you zero kilo kilohash. Difficulty is also known as the mining difficulty to find a new block. Let’s look at the next row, the bottom side. Average nodes or active nodes is just the number of nodes connected to the dashboard.The total number of active connected nodes powering the network is quite high. So right now you see 15 nodes are active. Yes. Next one is gas price. That’s the price the miners are currently accepting. Currently it’s at six or 7.5 gwei, which is 60 gigawei, which is 6 billion rei. So, the default is 20. The. Next one is gas limit. Gas limit is the gas limit for a block. The dashboard reads 8,000,029. And the miner can include transactions until the block is full and limit is met. The default is formally in 712388, which is 1.5 pound million gas. In bitcoin, you might have come across block size limit. So this is quite similar. So let’s look at the next one. Page latency. It takes 130 milliseconds, which is the dashboard stat. Uptime is also a dashboard stat. And then you’ll see a map in here. It’s a global map where all these nodes that are connecting into the dashboard. It’s just a dot represents which ones are connected to these dashboards right now. Okay, let’s let’s look at the next one, which is block time. In my dashboard it’s not currently showing up. But currently, it maps out to the actual time between blocks. So we looked at- it’s less than zero seconds, so that’s probably why it’s not showing up. Difficulty chart. That maps the actual difficulty of previous blocks. The next one is block propagation chart. That’s for the nodes connected to the dashboard. It is how fast the blocks are shared or propagated between nodes. The last block mines displays the public key of the miners who found the most number of blocks. Right? Okay. We went through the maps, so let’s come back to the next row which is uncle count chart. It’s got a green and blues in here. The uncle count chart displays the number of uncles per 25 blocks per bar. So each bar is five uncles per 25 blocks. Next one is transactions. That displays the number of transactions included in the previous blocks. The gas spending chart would show you something that’s correlated to the transaction charts, and it displays the amount of spent gas. The gas limit chart over here is dynamic in nature and it shows gas limit for the previous blocks. Please note, this dashboard does not represent the entire state of the Ethereum network, but it gives you a very good handle on what’s happening. Should you choose to, you can volunteer to connect to your node, to the dashboard for which you need to run an Ethereum node in your machine or in a cloud. The next set of rows over here that you see are basically in tabular format. So feel free to spend some time here, get to know the dashboard well and how the various numbers change as the network continues to perform. Okay, so let’s wrap this up. In this lesson we’ve covered the Ethereum network performance, dove into some of the metrics in how to inspect it. This tool and metrics will come handy when you start building your projects. In the next lesson, we will cover how transaction life cycle works in Ethereum.

20. Ethereum Command Line Interface CLI-OKTjNZjhCA4.en

By now, you must be eager to get some hands-on experience with the Ethereum tooling, various client types, different networks, wallet, and how to set up a death sandbox for your projects. So, in this section, we’ll learn how to download and setup in Ethereum Command Line Interface. The specific client app, we shall focus on is called go-ethereum. So, but before we do that, it’s important to know what other client types available, but just in case you need it for future reference. So, as you can see, multiple client implementations across different operating systems exist. The list of languages is Go, Rust, C++, Python, JavaScript, Java, Ruby, and Haskell. So, shortly we’ll work through the Go Implementation. The go-ethereum client is also referred as Geth. This is go-implementation to run a command line interface often ethereum node. By running this node, you have the option to participate in any of the live networks including the main and the test. Some of the functions are you can create accounts, transfer funds between ethereum addresses, you can create contracts, send transactions, explore blockchain history. Now, you can follow the instructions on this page and install the latest version of Geth on your respective machines and operating systems of a dash, the link to this page in the resources section for you. For example here, we will be installing Geth using Homebrew on a Mac. The command you want to run, it’s right there. So, you can say, brew tap ethereum/ethereum, brew install ethereum, or if you’ve already installed it, you can use brew upgrade ethereum. So, just go to the installation steps, it’ll say, so now the installation is done, let’s run the Geth Client and sync up to one of the tests networks. Later on, we’ll cover the various ethereum networks and sync modes. So, we’ll be syncing to the Rinkeby test network. The command you want to run is Geth. I’ll give you the command lines in a minute. So, it’s geth —rinkeby -syncmode “fast” and I’ve attached the link to this page in the bottom. So, the command like I said, it’s brew install ethereum or brew upgrade. I’ve already got ethereum installed, so I won’t do that. So, the command you would run as geth —rinkeby —syncmode so within double-quotes fast. So, when you run that, you will have something like this running. So, this is basically what they’ll run a process. So, once get this running on your machine or it’s syncing with the rest of the Ethereum network, every 15 seconds or so you will see a new block being imported. So, for every row, you’ll notice that the following fields are shown like you’ll have something call the blocks, the info, the blocks that transactions message gas, elapsed time, message gas, number hash and cash. So that’s typically what I wanted to cover in this lesson. So, having gone over some berries Client Types and witnessing how to download, install, and run Geth on Ethereum as a command line interface, it’s your turn to just give it a go and let us know if you run into any problems, just reach out to us in the community channel. In the next section, I’ll cover ethereum graphical user interface.

20. Ethereum Graphical User Interface GUI-__cAuQeUphk.en

If you prefer a graphical user interface over command-line interface, this lesson will introduce you to that. So, let’s head over to ethereum.org and got this up and running here, and download the Ethereum graphical user interface. I use a Mac so I’m going to go download that particular version. So you click on this button called download. So, the installation page would look something like this. If you use a different computer or an operating system, you click on all versions and you can bring the appropriate version. So, if you use a Linux, download the Linux 32 or 64, if you got a Mac, so I’m using Mac so, I’ll download this particular version here. After you download and you go to the installations, it’ll install the applications folder, and then when you bring it up, when you launch the application, the Ethereum graphical user interface would look something like this. So, what it contains basically, right now I’m connected to the test network, so you got the main Ropsten and Rinkeby, some connect to Rinkeby. In this illustration, you got four accounts Mist account 1, 2, 3, 4. I’m on accounts overview. One thing to note is the ether that I have over here, it’s play ether, so, you can use this ether in the main net, so, this only work under incubator network. So, give this a crack, see you’re able to installed the graphical UI with the Ethereum wallet in the Mist, and if you don’t have any accounts, I think it’s usually have one account to begin with, and you can try adding new accounts as well. In the next lesson, what I’ll do, I’ll show you the different network types and how you can connect through that.

21. C4L1-18 HS-A Lesson Recap-2Kh4MXWfnXY.en

Congratulations. You made it through the lesson, Introduction to a Ethereum. We covered a lot of ground in this lesson. Let’s do a quick recap on what we learned. First off, we did a refresher on blockchain framework. Then, we learned some Ethereum basic terminology, plus the roadmap and consensus algorithm. Next, we did a bit of a compare and contrast on proof of work versus proof of stake, checked out some tools to monitor network performance, and learned how private keys, public keys, and addresses are generated during their transaction lifecycle in Ethereum. In preparation for the projects ahead of you, you also learned how to download and install the Ethereum Command Line Interface, Ethereum Graphical User Interface, Ethereum wallet, Minimalist wallet, and how to request for play Ether from the various forces. We even managed to create a simple transaction in the Ethereum network. Before we say our goodbyes, please join our discussion group and participate in the various conversations about these topics. Should you have any questions, please do reach out.

img

Part 05-Module 01-Lesson 02_NEW Introduction to Solidity and Creating a Token

01. C4L3-01 Lesson Intro-Q46xjAxGIYw.en

Welcome to our lesson on solidity. I’m going to be your instructor for this lesson. Have you always wanted to be able to write your own smart contracts? Have you wondered what token contracts are? How about creating your own tokens and then being able to view them on EtherScan? Or, how about being able to send your own tokens to your friends? We will cover all these topics in this lesson. We will start with learning solidity, the main language used to write contracts on Ethereum. We will then learn the syntax of this language, and then look at many samples, smart contracts. Once we get comfortable with this language, we will then talk about token contracts and token standards. Next, we will show you how to create your own tokens and then send them to your friends. Lots of exciting stuff to learn in this lesson, so let’s get started

02. C4L3 Concept 2 Part1 V2-tI2YSDI1rAE.en

In this concept, we will learn about the basics of a Smart Contract. What is a Smart Contract? It is a piece of code that lives on the blockchain network. It can be instructed to do many things like send money, receive money and other assets. Ethereum gives us the option to run code or programs out of the participating nodes. This code is called the Smart Contract. It lives on the network. The most common language that is currently being used to write Smart Contracts is solidity. There are few other languages too, but this is the main one. Smart contracts have an account address just like a wallet address. They can also hold Ether just like wallets can. They also have their own storage where variables and other data is stored. Let me explain a sample Smart Contract by a simple use case. Let’s say a buyer wants to buy some budget from a seller. Since there is no centralized authority involved in blockchain, the buyer will first send the required amount of Ethers to a Smart Contract. The contract will hold these funds like an escrow. Now, the seller will ship the item to the buyer. As soon as the buyer receives the item, the buyer will instruct the contract that the item has been received. This is when the contract would release the funds to the seller. Now, you see how the need of a third party is eliminated by using a contract to perform the same actions. The most common language that is used like I mentioned to write the contracts is solidity. Serpent is another one. You can also use some other lisp-like languages.

02. C4L3 Concept 2 Part2 V3-DtOOiPevC3k.en

I’m going to now walk you through a simple life-cycle of a contract. This will really help you understand this topic from a broader perspective. So, we start with developing or writing a contract, then we deploy it to a local test network or any of the public networks. Once deployed, we get an address back as to where the contract is deployed. Using this address, we can invoke it and call various functions on it. Once a contract has finished its purpose, it is always a good idea to destruct it, which means that no one can call functions on it anymore. Let’s look at all these various steps that we’ve just talked about. For writing a smart contract, like I already mentioned, we will be using solidity for this course. You can use Visual Studio Code with Solidity Plugin added to it. You can also use any of your favorite editors or you can always use truffle. Or the best way to get started is to use remix online editor. I will walk you through remix in the next concept. Also, wanted to mention that solidity files have a.sol extension. It is a strongly typed language what that means is that the type of the variable should be defined when you declared the variable. It is similar to JavaScript syntax wise, but I personally think there are quite a bit of differences too. Moving on. Once you have written a contract, the next step is to compile it. The compiler output two things, the byte code and the ABI. ABI stands for Application Binary Interface. Byte code is what is deployed to the network, this is more like machine-level code hard to understand. But ABI is also sent along. ABI is actually used to interact with an already deployed contract. ABI is more readable. If you look at the ABI, we will see what variables and functions the contract has. So, we can call these functions from our application side. Like I already mentioned, after compiling, we deploy a contract to any of the public networks or the local test network. Let’s consider the Rinkeby public tests network. Once we write a contract, I want you to imagine like a class in C or Java. When we create a class, they may create instances of the class, right? So, this contract is just like a class. When we deploy it, we actually deploy an instance of the contract. So, if we deploy this contract multiple times, we create different instances everytime. Every instance of the contract will have its own address. After deploying the contract, we will get an address back. Now, this is a contracts address. To invoke it, we will need this address. They can use online wallets to interact with their contract. There are desktop wallet too, like the Ethereum wallet. There are also hardware wallets like Ledger, Trezor. As programmers, you can also write your own DAP, which stands for decentralized application, that uses Web3 interrupt with our contract. Web3 is the only programmatic way that can connect any front-end application to the Ethereum world. I’m going to now walk you through a basic smart contract layout. If you look at the first line the pragma, the pragma would specify the version of solidity that we’re writing inside this file. When this code is fed into the compiler, the compiler will look out for the specific version. So, your code does not break. The word contract is similar to classes in Java. Remember, all these contracts that you and I are writing can really be thought of as being classes, and when we deploy these contracts to any Ethereum network, those deployed versions can be thought of as instances of this class. Then you define your storage variables. Now, these are variables that will exist for the life of the contract and are automatically stored along with the contract on the blockchain. Any variables outside the functions are called storage variables. Then we declare our events. The contract can emit events when certain conditions are met. They can write the frontend application, the watch for these events, we will talk about more events later. Then we have a function defined. This is just a sample smart contract. It starts with the pragma line, then we define the contract with the keyword “contract” and then the name of the contract. The word string means that this variable will only ever contain a string. Public means who has access to look at the contents of this variable. Then we have the name of the variable. We will talk about the syntax in detail in a future concepts. Then we have our constructor function. This is declared with the keyword “constructor”. This function is automatically called when we initiate the contract. We can pass any initial arguments right here to the constructor function. Then we have a getName function. One thing I wanted to mention is that. Anytime we create public storage variables like name in this case, an automatic get function is created for this variable. So, the getName function is not required at all. But I just wanted you to look at this so I could explain you that this function is not required. The next is the setName function. This is now just a high level view of what the smart contract looks like, we will cover all these topics in detail in our future concepts.

03. C4L3 Concept 3 Remix V2-u46Eec0MbvI.en

In this concept, I will give you a walkthrough of Remix, the online editor. Remix is an online tool that can be used for writing, compiling, debugging, deploying, and also invoking smart contracts. It also creates a simulated Ethereum network inside your browser called the JavaScript VM. VM stands for virtual machine. It gives you various environment options to connect it to the world of Ethereum. I will explain you this more in detail soon. This is what Remix looks like when you open it up. You will see compile, run, debug, analysis, and testing tabs on the top. You can create new files by clicking on the very small plus button on the very corner. Remember, solidity files have.sol extension. In the central area is where you write your code. One thing I totally love about Remix is that it is a syntax checker. It has a fantastic syntax checker, which means that the moment you write something wrong, it gives you red arrow right there and detailed description about the error. Amazing feature. From the compile tab on the top, you can select the compiler version that you would like to use. You can also set it for auto compile. From the run tab and the environments, you can choose JavaScript virtual machine, injected the three option or the third one is the Web3 Provider option. You can deploy your contract to the in-browser simulator by using the JavaScript VM option. You can use injected Web3 option to deploy your contract to any of the public desk networks or even the main network. This option works in conjunction with MetaMask. You need to have MetaMask installed for this to work. The reason this is called injected Web3 because MetaMask injects Web3 into your browser and also hosts a node. So, injected Web3 option lets you connect to the Ethereum network through MetaMask’s node. Let’s have a quick recap again. You can use JavaScript VM for testing contracts. It is very fast since there is no mining. Injected Web3 option is used in conjunction with MetaMask and can be used to connect to any public network. Whichever network your MetaMask is connected to, the injected Web3 will connect to the same since that is being injected into your browser. Remix also gives an option to deploy your contract to locally running node on your computer. You will choose the Web3 Provider option for this and we will provide the URL or the port number for your locally running node. In the transaction origin or the account field, you can choose the account you want to use to deploy your contract with. This list of accounts will change based upon the environment you are connecting to. For the in-browser network, you are given 10 preloaded test accounts, and this account list will be those accounts. If you’re using injected Web3, then this will be a list of MetaMask’s account addresses. For the Web3 Provider option, this account list will be your locally running nodes accounts that you have. Gas fields let you specify the amount of gas that you want to use for this transaction. In the value field, you will provide the amount of ether you wanted to send along with the transaction. Moving on, you can deploy a contract by using any of these environments using the deploy tab. You can also pass constructor arguments right here when you initiate a contract. If you are connecting using the injected Web3 option, you will get a confirmation screen from MetaMask to accept the usage of gas charges. Once deployed, you will see a list of functions on the side. Right? If you look on the right side, you will see a list of functions that are all available on the contract. Now, you can interact with all these functions and pass arguments. If the argument that you are passing is a string, make sure to use double-quotes since it is expecting a JSON format. The bottom gray-colored console shows you the status of every function call and a transaction hash. This window will also give you the deployed contracts address. You can also see the transaction hash for every transaction in this window. You can also look at ABI and the bytecode of your deployed contract by clicking on compile and details tab. You can also load an already deployed contract and interact with it. Just paste the contract address in at the at address text box. This will pull up the contract and give you all the functions that you can call. To summarize, Remix is an online tool to create, write, debug, deploy, and interact with smart contracts. You can use an in-browser network for testing your contracts. You can also use or connect to a locally running Ethereum node or you can also connect to any of your public networks using MetaMask. Now that we have a clear understanding of how Remix works, let’s learn solidity language. I will be using Remix as our tool to learn and write code from now on.

04. C4L3 Concept 4 Memory Management V2-H6IYcwFG2Po.en

In this concept, we will learn about how memory is managed in solidity. We will talk in detail about these topics as we move onto more relevant concepts, but I wanted to give you a little high-level overview on these keywords. Let me introduce you to the keywords memory and storage. Memory is divided into three areas, storage, memory, and calldata. As a developer, you can use the keywords memory, and storage. Let’s talk about storage first. Now storage, think of it as a database layer where contract’s data is stored and persisted. Read and write operations are costly for storage data. Memory is for temporary storage and is used for call code execution. You can allocate memory for complex types like arrays and structures. The data in memory is lost after execution. Calldata area is like a call stack, it is temporary and non-modifiable. It is used for function calls, maximum size is 256 bit boots. Now, if you have multiple recursive calls, it can lead to call stack error. For now, the main point that I really want you to remember is that, state variables are always stored in storage. Now, these are the variables that are outside any function. Local variables inside functions are just references to data in storage. Data for function arguments by default, is located in memory. You can use the keywords, storage and memory to change this default storage behavior. I don’t want you to be overwhelmed with this information right now, it will get more clear as we move on to relevant topics. Now, just to recap again, by default, like I mentioned already in a previous slide, all state variables in the beginning of the contract outside any functions that are not inside any function are stored in storage. So, you don’t have to specify the word storage, they will automatically be stored in storage. Hence the count variable, if you look on the code on your screen and also the array points, are all by default going to be in storage. For local arrays inside any function, they should be specifically labeled as storage or memory. Now, if you don’t put a label, it is going to put in storage, but the compiler will still compile, give you compiler error and ask you to label it as storage. It will still compile, but it’s going to complain that it really likes to see the word storage over there. Now, we can specifically change the default behavior and store it in memory, like we are doing in the memory array example on your screen right now. The pointer array that you see here is inside a function, this is fine just because it is pointing towards an array in storage. Now, this is just a high-level overview of memory types. Again, we have three types of memories; memory, storage, and calldata. You are going to be using these words memory and storage quite often, especially when you use strings, bytes, and every types as we move forward. So, as we get into complex data types, we will discuss these topics in more detail.

05. C4L3 Concept 5 Basic Data Types V2-vw3xEXYEmKc.en

In this concept, we will learn about elementary data types. As mostly all languages have, Solidity has elementary data types and also complex data types. In this concept, we will explore the elementary data types. We will talk about int, uint, bool, and address types. For signed numbers, you will use the int type and for unsigned numbers, you will use the uint type. You can also specify the size of the integers in 8-bit increments. For example, uint8 means eight bits or one byte, which means it can hold a number between 0-255. If it don’t specify any size by default, int means int256 and uint means uint256. That means it can hold 256 bits, which also means a 32-byte number. Bool is another elementary data type and can hold true or false values. Any logical operations like the AND operation or the OR operation will all lead to a Boolean value. The next elementary data type is address. It represents an address of an externally owned count or even a contract account. It is a 20-byte hex string. It is a value type. Address type also has methods that you can invoke. Balance is one method. So, you can get the balance of the account or the contract by saying address.balance. Transfer is another method and so is send, and these are used to send Ether to another address from the current smart contracts address. Now, what you see on the screen is an example of an address type. The name of the variable here is owner. In the second line, we have another variable called initial balance that is of type uint. Then, inside the function set balance, we are getting the balance of the owner by using owner.balance and storing it in the variable initial balance. Next, I want to explain you the initialization of these basic data types. If you don’t specify a value, what Solidity does it initializes all uint and int types to zero, and bool types to false, which means int num will be initialized to zero, uint32, another value will again be initialized to zero, and bool value will be initialized to false, and address type and all the address types are initialized to a zero address. See if you look at the last line here, address of owner, so if you ever wanted to check if this variable owner has been initialized or not, we can just compare it to zero address. Now, let’s walk through some sample codes using data initialization. Okay, so what you see on the screen is a very simple contract and the name of this contract is BasicDataTypesContract, and we are, of course, going to go to the syntax and all that stuff more in detail. But, if you start see our contract start to the line pragma, and then we have contract, and then we have the name of the contract. Now, within the contract, we are initializing a variable a, of type uint8 and storing a value of 255 in it. It’s going to work fine just because in int type, which means eight bits can store a value between 0-255, so the compiler will not complain on this line. In the next line, if you see we have an address variable. The name is owner public. That means anyone can view it, and it’s called owner, and the next line, we have a bool type variable called flag. Again, public and we’re setting it to initially zero. Then, we have a uint type variable, called ownerInitialBalance and this is again non-initialized for now. Like I mentioned, if it’s not initialized, it’s going to initialize to zero. That’s what Solidity does. Now, then we have a function here, and the name of the function is test. It is taking in one argument address type. The name is address. It is a public function. We will look into funk functions and the syntax in our future concepts. For just now, just go with the flow here. Now, this function returns a uint type variable. Now, inside the function, what we’re doing, we’re actually taking the address that is being passed as the argument and storing a DC owner, and then what we’re doing whatever the address is coming as the argument, we’re getting the balance of that address and storing it in this variable that we had declared globally, non-initialized right here. Now, this is something I just wanted to show you like we mentioned that all Boolean values are initialized to false, and also Boolean values, you cannot just put like a one in here. In many languages, you can just put a one and this will evaluate to true. Solidity, in fact, expects an expression. So, this is going to give an compiler errors. If I delete this line here, the compiler’s going to complain because it’s not expecting this. So, just to show you that. Now, this will work fine because you’re after getting a Boolean value. So, one greater than zero and, of course, comes at the output is true which means now this code will be fine. Then, again, in the function, now, this is just a sample code, is not doing anything here. I just wanted to show you a couple of different features of how things work. So, just to show you is this here, and now what we’re doing, so again going back, we had the address, we store it in the owner, and then we got the balance of and store it at the owner initial balance and now we’re returning that, and this is the return type you want, okay? So, if I, in fact, I can show to deploy. We’ve looked at Java’s Remix before. So, let’s go deploy this contract. Once you deploy this contract, you can click on this button right here. Now, we’ve set the value of flag true, it’s going to output true. Owner as of now is not set because if you see the owner is being set in this function. So, as of now, we haven’t clicked on the function test yet. So, if I get the owner, it’s going to say zero. Now, let’s go call the function test. What I’m going to do, I’m actually going to pick one of these values. You can click on this button copies. If you said “Copy to Clipboard”, it’s going to copy this address, okay? Now, I’m going to put in place this address right here, and now I’m going to call the test function. Now, when you call the text function, you can click on this arrow right here and brings up this window, and let’s click on this last thing that we just had. Now, let’s call the function again and you will see that the owner address has been changed to the one right here. In fact, in the balance like you see this function is returning the balance, so if I click on that and look on the output, so this function is outputting the balance. If you see this balance of this address, the uint of the output right there, the return value is this value 9999 which matches the balance. Now, this is how you look at the balances of the contract addresses here, so the balance of here matches. This value right here in the way, of course, this is an Ether and this is in way, so it’s giving you that value right here. So, it matches. So, again, just a simple way, it’s a very we’re going to definitely get into more complex contracts soon, but this is a very simple one just to show you how things work in Solidity. So, we have some basic data types here, uint type, you have an address type, we have a bool type, and then I wanted to show you how you cannot compare or evaluate something that’s not an expression, has to be an expression, and you can also run contracts and functions and deploy contracts to this function.

06. C4L3 Concept 6 Type Conversion V2-PPsT3oeqePI.en

In this concept, we will talk about type conversion in solidity. All programming languages support some kind of type conversion, and so does solidity. There are two types of type conversions available to us, implicit conversion and explicit conversion. Implicit conversion. Let’s talk about that. The compiler will attempt to convert from one type to another type if there is no loss of data. If there is potential loss of data that means, if we are trying to convert a variable from uint32 to uint8, there will be loss of data, right? This is when the compiler will give you an error. But if we’re trying to convert uint8 to uint32, the compiler will not complain since there will be no loss of data. Let’s look at some examples in front of you. In the first example, uint8 a is equal to 255 is going to work fine since uint8 can hold one byte of information, hence it can hold numbers up to 255. In the second example uint8 is equal to 256, the compiler will give an error since one byte cannot hold a number greater than 255. In the third example, we have int8 a is equal to 255 then we have int c. Now remember, whenever you do not mention a number, int c means int 256 c. Then we are doing c is equal to a. This is going to compile perfectly fine without any errors since int c means int 256 that means it can easily hold a byte of information. Let’s look at some more examples on your screen. In the first example here, we are declaring a as uint 256, then we are declaring b as uint8. Then we’re trying to do b is equal to a. We are trying to put the value of a in b. This will give us a compile error since b cannot hold or b can actually hold only eight bits and it cannot accommodate larger numbers. In the next example, we’re trying to have a Boolean expression in the brackets and they’re doing if brackets one. So, we’re evaluating an expression with the if statement. Now, in some languages, one will evaluate to true but not in solidity. You need to explicitly give an expression. So, this is going to feel since one cannot implicitly convert to true. In the next example, if one greater than zero, now this is going to pass since the condition is now evaluated to true. Now, let’s talk about explicit conversion. You can explicitly tell the compiler to convert from one type to another type. There could be potential loss of information and you are aware of that. In the next example that you see on the screen, we have a 32-bit number then we have a 24-bit number. Implicitly, if you try to store the 32-bit number in the 24-bit number, we are trying as we’re trying to do in the second line, the compiler will give an error. But you can explicitly convert the 32-bit number to a 24-bit number by enclosing it in a bracket like on the third line and this is going to work perfectly fine. Let’s look at some more examples for type conversion now. So, let’s look at this simple example for type conversion. So, a very simple contract not really supposed to do anything just show you and explain you some type conversions in our language. CPC, it starts with a pragma line, solidity version that we’re using right here and then word contract declares that this is a contract and then the name of the contract. Now, within that, all these variables that are outside any function automatically they become storage variables. So, we have the first variable which is a one byte unsigned integer because it says uint8, and then we have a uint 256 because it doesn’t see anything and other variable. Now, inside the function, which is the name of the function is conversion and we have int b which means it is a 256 bits or a 32 byte signed integer. Then we’re trying to do b is equal to a. Now, this is going to compile successfully because a 8bytes type can easily fit into 32byte information, right? But the next statement is going to give you an error and I’m going to show you by uncommenting this. So, if you see the compiler throws a red arrow right there, that shows that this is not going to work, so I’m going to comment it back. In the next line, if you see I’m actually explicitly converting b to uint8 and then storing it to a. Now, this is going to work perfectly fine because we are doing an explicit conversion in this example. All of these sample contracts are going to be available on our GitHub page so you can download them, play with them, and really get comfortable with all of these different concepts.

07. C4L3 Concept 7 Complex Data Types V2-bxAUX1DNdRc.en

In this concept, we will talk about various complex data types available in Solidity. So, the various types that we have are; arrays, structs, mapping, strings, bytes and enums. Now, complex data types are managed quite differently in memory than basic datatypes. Complex data types also need memory allocation to persist and recall execution. I’m going to explain you all these concepts in detail as we talk about the different types. Starting from the next concept, I will explain you this complex types one by one.

08. C4L3 Concept 8 Arrays Sound V2-PnNjBiETXik.en

In this concept, we will talk and learn about Arrays in Solidity. There are mainly two types of arrays: static arrays and dynamic arrays. The syntax for static arrays goes like this. So, you have type of array followed by size of array in square brackets and then the name of the array. If the size is left empty inside the square brackets, then you end up creating a dynamic array. Static array means to create an array of fixed size. Dynamic arrays don’t have a fixed size. So, on your screen right now, let’s look at the static array section, bool[10] array. Create a static array with the name array that can hold 10 elements. We can access individual elements like array element at index four. In the dynamic array section, we can create dynamic array with no size inside the square brackets. In both static and dynamic arrays, we can get the length of the array using the.length operator. For static arrays, we cannot change the length property, but for dynamic arrays, we can, only if they were stored in storage. Arrays behave quite differently in memory versus storage. Let’s talk about creating an array, and which is again dynamic versus static array, so I am going to look at both. Let’s look at the static arrays section again. Now, we’re trying to create a bool static array and then a uint static array. For dynamic arrays, let’s consider both; storage and memory arrays. For both storage and memory dynamic arrays, we can allocate memory using the new keyword. So, you can create an array and then you can allocate memory using the new operator. You can push on dynamic storage arrays. You can specifically use the keyword memory to create an array in memory. For dynamic memory arrays, you cannot use the push method. This is a very, very important piece of information, and I really want you to remember it. So, again, you cannot push on dynamic memory arrays. Let’s talk about initialization arrays. So, how do we initialize arrays? In the first example, we’re declaring it as a uint8 static array, and then also initializing it with uint values, so the compiler will be fine with this. In the second example, the declared array type is int, and the initialized type is uint, so the compiler is going to throw an error. In the third example, we just need to apply explicit conversion to one element of the initialization data, and the compiler will now be fine with this. Let’s take my array as an example here, the one that you see on the screen. So, we cannot initialize dynamic arrays in memory. The reason is that the compiler implicitly creates a static array which is not compatible with dynamic arrays in memory. So, just remember, you cannot initialize dynamic memories array in memory just like this. It’s going to give you an error. Now, let’s look at some more examples here. In the first line of code, this is going to give us a compiler error. Why? I just explained that to you in a couple slides before. Since dynamic memory arrays cannot be initialized like this, like we saw in just a couple of slides back. In the second line of code, we are creating a memory dynamic array and then the third line of code we are trying to push on it. This is also going to fail. Again, can you answer why? Since we cannot push memory arrays and again, I explained that to you just a couple of slides back. Moving up, let’s look at some more examples for arrays. In the very first example, we are creating and also initializing the array at the same time. The first line of code will compile without errors. Since we are creating a static array of three elements and then we’re initializing it with two elements, the last element is initialized to zero. In the second example, we’re creating a static array to hold three elements but we’re trying to store four elements. This is going to give us a compile error, since it cannot hold four elements. Let us summarize arrays. Some very important points of arrays you really need to remember. First of all, solidity supports dynamic arrays and static arrays code. There is a difference in how memory and storage arrays are treated. The first one is that you cannot push on memory arrays. So, remember, you cannot push on memory arrays. Next one, you cannot change the length of static arrays. Next one, you cannot initialize dynamic memory arrays like the 1, 2, 3 assignment on your screen. So, again, for dynamic memory arrays, you cannot have initialization like this one. Now, let’s look at a sample contract to understand and look at all these things that we’ve just talked about. Okay. So, on this sample contract that we have in front of you. Again, I’m going to recap pragma solidity, the name of the version, then the contract word. A very simple view of creating a contract, we’re using Remix for all these sample contracts for now. We are going to be giving you code, so you can actually copy and paste this code in your Remix editor and play around, change values, and really learn all these topics nice and well. Okay, so let’s start. So, we have created three types of arrays here. The first one is a static array but size three of type int, and we’re also initializing at the same time. So, we’re giving it two values, that means the last element is automatically going to set it to zero, and then we’re having a dynamic array of type int8. No number in the brackets, that means it’s a dynamic array. The next we’re creating a bool dynamic array, the name is dynamicBoolArray. Now, we have a function, and the function’s name is testArray. Now, in the function, what we’re doing is that we’re actually allocating memory. We just created an array here. If you see, we have a dynamic bool array. Now, we’re actually allocating memory and this is how you do it. So, you create an array, a dynamic array, and then you allocate memory for int elements with this statement here. Now, in the next statement, what we’re trying to do, we are doing an explicit conversion as needed, for sure, just because you have to convert from uint8 to int8. So, if you see I’m trying to convert from uint8 to int8, since the dynamic int array is of type int. So, I’m going to convert my 1, 2, 3 numbers which are uint to int to do this. So, this is perfectly going to be fine. The second line is also going to work fine, right here the uint8 memory memoryArray. You can definitely create memory arrays like this; you cannot do it outside functions. Outside functions arrays are definitely, by default, are going to be stored in storage. If you put a memory word, the compiler is going to complain about that. But inside functions, you can do storage or you can actually, forcefully, just put the word memory so that you want to make sure that this array is in memory. So, that worked fine. Now, we just talked about that, you cannot do this kind of assignment for dynamic memory arrays. So, assignment of dynamic memory arrays is not allowed. If I uncomment this, you will see the compiler gives an error. So, this kind of assignment for dynamic memory arrays does not work. Again, we’re allocating memory for the memory array that we just created here for the new operator. Now, we also saw a couple of other things that we cannot push on memory arrays like this. So, if I uncomment this I’m going to get an error. We also cannot get the.length for memory arrays like this, even that gives us an error. Now, for static arrays, we can do this kind of an initialization. So, if you see this kind of initialization for dynamic memory array was giving us an error, but for static array, it’s perfectly fine. So, we’re initializing the array with 1, 2, 3 elements, it works fine. Then, we’re creating another memory static array, memory word static because it has a number in the bracket. Memory, because we’re putting the word forcefully memory because we’re inside a function. Now, this assignment is allowed because it is a static memory array but if it was a dynamic memory array like we saw is going to give an error. So, this is going to work fine. Again, we’re doing an explicit conversion to store in the static memory array. Now, what again is allowed. You can always store individual elements, those are perfectly fine. So, you can access individual elements and store a value. So, this works fine for static memory arrays and also dynamic memory arrays. Now, these are some of the things I definitely wanted you to focus and learn. The really important one is that you cannot push a memory array. So, this is a very important one. You cannot initialize dynamic memory arrays this way. So, these are a couple of really important points that I really want you to remember, and I would definitely encourage you to watch this video again. Because, a couple of times you watch it, the concepts will definitely get clearer. So, I want you to copy this code, bring it into your Remix, play around, change values, and really try to get the concepts nice and clear in your head.

09. C4L3 Concept 9 Strings Bytes V2-EBoPPXVaza4.en

In this concept, we will talk and learn about special arrays, bytes, and string type. Now, bytes type and string type are both special arrays of type byte data. There are many similarities between the two and also many differences. Since they are special arrays which means they can also be static or dynamic just like regular arrays. They can also be created in memory or in storage just like normal arrays. Now, how do we initialize and create bytes type? Bytes type array can be created in two ways; either with the keyword byte and the square bracket notation or with the keyword bytes. If we look in the static section on the screen, we are creating the data bytes array using two notations, either with a byte word and then the square brackets notation with the number inside the bracket or with the bytes would followed by a number between one to 32. Now, let’s look at the dynamic bytes section array, So, dynamic bytes array can be created with the word byte, empty square brackets or bytes notation. Of course since they’re dynamic, we won’t need to give a size. Now, there are some restrictions on static, which means fixed byte arrays. Fixed-size byte arrays are read-only, so you cannot access them using index or store a value since they are read only. You cannot modify the length property EPC in the example data is a 24 bytes array, bigger is a 32 bytes array. So, we cannot store bigger into data. But smaller is a 16 bytes array, so we can store smaller, that is a 16 bytes into data that is 24 bytes array. A smaller size byte array can be assigned to a bigger size byte array but the other way around is not allowed. Moving on. Let’s talk about string type now. String first of all is not a basic type, it is not a value type either, it is an array of bytes, it is dynamically sized. Now, there are many similarities and also many differences between bytes type and string type. Let’s first of all talk about conversion between string type and bytes type. In the function convert that you see on the screen, we are converting a dynamic bytes array to a string just by enclosing it with the word string, this is how you convert between one to the other. Inside the function again, the next conversion is from a string type to a bytes type just by enclosing it with the bytes keyword, just the way we did for strings. Now, let’s look at some differences between string and bytes type. In string type fixed length is not supported but it is supported in bytes type, just like we saw before by using one to 32 number after the bytes keyword. Index access is not allowed in string but it is okay for bytes type. In fact, this is a very important point since we cannot access strings using their index you will see in many codes where we tried to convert a string to byte and then access it using an index, we will see an example of this soon. We cannot push on strings but on storage bytes type, we can push. But remember, we cannot push on memory bytes type, we’ll also see an example of this soon. Now, let’s look at some examples on the screen in front of you. We have a variable string storage that is an initial value of Udacity. Then we have a function called convert that takes in a string argument and returns the length of the string. We will look at functions more in latter concepts. Since we cannot find the length of the strings or strings especially in this case, we will convert it into bytes variable temp and then find the length of the variable temp and return this value. The next function called get element at, we are getting an argument index and then we’re returning a byte value at this index. Since we cannot access strings using an index, we are converting the variable string storage into bytes first and then we’re accessing the index. Since this is just a byte, we’re storing it in a byte and then returning it. Now, these are all very usable benefits of being able to compare and convert between strings and bytes. Let me give you some more details on strings. First of all, there’s not much out-of-the-box support for strings in solidity. There is an external library called StringUtil, that I would really encourage you to look at that can be imported that provides some functions that we can use on strings. Also, complex string operations should definitely be avoided because they are very costly on the EVM. Many similar operations can be carried out using bytes type. Another better option would be to carry these operations in a front-end application rather than on the EVM. Let us summarize string and bytes. Bytes are in an array of bytes type. Fixed bytes type can be created by saying bytes one, byte two and so on. Dynamic bytes can just be created by using the word bytes. String type is similar to bytes type. Fixed length strings are not supported. We cannot push on strings very important, we cannot push on strings. Indexed access on strings is not supported, a common practice is to convert it into bytes type and to have index access. Now, let’s look at some sample contracts so that we can understand this concept further. So now on our screen, we have a sample contract called Stringbytes, contract Stringbytes. Now, we’re declaring two ways I’m going to show you like I just mentioned, we can have restarted declare initialize two ways, so the first one is a static byte array, both declarations will create an array with three byte elements, one with the keyword bite, square bracket notation, and the other with a keyword bytes3. In the second one, we have dynamic bytes array, byte followed by this and then bytes and then bytes array. Then we have a string variable that restoring and storage just using this. Now, inside the function conversion test, we’re returning a string. So, what we’re doing we’re creating a string two in memory, storing value Udacity, and now we’re converting it into string and then returning the string. So, I’m showing exactly what I showed in one of my slides you can convert a bytes type into a string type by converting it or this way and then I’m returning the converted value. Now, this is a very important function I definitely want you to focus at. Now, this is a way that you definitely would need in many pieces of code where you’re trying to access an index, which we cannot do in strings. So, what I’m doing is I’m converting my string to bytes and then I’m accessing it using the index. So, in this function I’m actually getting a request saying someone wants to look at the index at this specific value. So, I’m using that index and I’m retrieving it and I’m returning that element. Now, since it’s just a byte information, so I’m turning a byte right there. The next function called testing, we have a fixed byte array that we’re declaring this way. Now, it is, first of all remember this is a uint8, so it needs to be explicitly converted to byte type. Assignment is also not allowed as bytes3array is a static array. So, bytes3array that we declared here was a static array, so that means if I uncomment this, this kind of assignment is not allowed in solidity, that we just talked about in this lecture. Now, we are declaring a bytes memory array, dynamic memory array, So, dynamic just because there is no word here, no number here, so that’s a dynamic array in memory called memory bytes. We’re allocating space for 20 different locations for this, now we’re accessing it and storing this value. So, this works fine but this did not work fine. So, this you can do that from memory arrays but you cannot do that for dynamic arrays like this. Push is definitely not allowed that’s in for a very important piece of information. Push is going to give a compiler error as Push is allowed for storage only. You cannot push on memory bytes arrays like this, I’m going to uncomment this and it gives me an error, so I cannot push. The next example, a very simple example, I’m just having a String memory and I’m storing a value in it and all I’m doing is returning, so you can return strings from functions this way. Again, like just like arrays, I would definitely encourage you to read this, learn these concepts, watch the video maybe one more time, and use this code, we’re going to give you all these code in your GitHub pages. So, copy this code, bring it to remix editor, change values, play around and I guess that’s the only way that you’re going to definitely get comfortable with arrays and bytes and strings in solidity.

10. C4L3 Concept 10 Mapping V2-a8e3A8-R-S4.en

In this concept, we will talk and learn about another complex type called mapping. The simplest way to describe mapping in solidity would be to say that it is similar to a Java hash table or a JavaScript associative array. Now, mappings are stored on the EVM as part of the contract. Mappings can only be created as a storage variable. Mappings can not be created as a local variable inside a function. In this example, a mapping named balances, like you see on the screen, will be created in storage, where key is of type address and value is of type unit. Now, keys can be of any type except mapping type, but values can be of any type including mapping types. So again, remember, your keys in a mapping can be of any type except the mapping type, but the values can be of any type including mapping types. Now, let’s compare mapping with hash tables. In mapping, values exist for all possible keys initialized to zero or empty strings. In other words, if you try to get a value for the key that was not set, then you will receive all zeros or empty string depending on the type of the value. When you add a new key value pair in mapping, the key is not stored as is. Instead, a keccak256-bit hash is created and stored as a key. In other words, the actual key data is not stored in the mapping. Now, mappings are not iterable, that means you cannot loop through mapping. There is absolutely no out-of-the-box way for looping through all the keys in a mapping. You cannot find the length of mapping. So, there is absolutely no way, no attribute or member function to find the number of key value pairs in a mapping. You can do this by maybe maintaining a separate counter for a mapping, but you just cannot look through the mapping, you cannot find the length of mapping. Now, let us look at an example code on your screen here. In this example, we’re creating a mapping called capitals. The syntax is to write a mapping is with the keyword mapping, then brackets, and then the key and the value types separated by a fat arrow and then the name of the mapping. Then, we have a function called addCapital, that is taking in two inputs: country and capital names. Then, we store this in the mapping. The various store keys is again using the square bracket notation. So, you give the name of the mapping, then a square bracket, and the key inside it. Then, ‘equal to’ sign and then you give the value you want to store along that key. The next function, getCapital. We are accessing the mapping using again the square bracket notation. To remove a key value pair or to initialize the value to an empty string, you can use the delete operator. This is what we’re doing in the function removeCapital. Let’s look at some more mapping examples and sample contract to understand mappings better. So, on our screen here, we are having a sample contract, and the name of the contract is mapping contract. It’s creating a mapping in storage, like I mentioned, mapping can only be created outside functions in storage. So we’re creating a mapping. The key is a string type, the values also string type, and the name of the mapping is relations. Now, what we’re doing is we’re having a function to add relation. So again, this is a mapping that just stores the relations between people and the relation to them. So, we’re having a function. Into this function, you can pass the name of a person and the relation to that person, and it’s going to access the mapping, store it. Again, name of the mapping, square bracket, key, value, okay? So again, name of the mapping, square bracket, you put the key, whatever your key gotten in the function followed by the value. This is same thing, is actually, accessing the mapping and returning. So, it’s giving you, the function is getting a name of the person, and you want to see what the relation is, so it’s returning a string. So, you again accessing it with the relations name and this whatever the value is going to be sent back. The way you delete it, if you’ve seen the next function, we have a removeRelation function. You have a string name, so it’s going to tell you the function is actually asking for an argument, who do you want to delete from my relations, and do you have the delete? Then, within delete, of course, you’re going to have brackets, and within delete, you have relations, you’re accessing the key value. This is a value that you’re getting and then you delete it. So, this is a sample contract that kind of explains to you mapping. A very simple contract, but mappings are definitely very important, that we’ll definitely be dealing with mappings quite a bit more.

11. C4L3 Concept 11 Enums V2-JbFQ4aYeFOE.en

In this concept, we will talk and learn about enums in solidity which are another complex types. You can create your own custom types with a finite set of values using the word enum. After the word enum, like you see on the screen on the example, then we have the name of the enumeration, and then in curly brackets, we will give the values. Note, there is no semicolon in the end. Now, enums are not a part of the ABI definition. What that means is that the color of the contract when looking at the ABI will not know if enums are defined in the contract. So, now, the question is, then how will we do or receive our path enumeration values in contract invocations? For that, you will use the index assigned to the enum values. In the example on the screen, we are creating a transfer type enum. It has two values inside it. Domestic has an index of value zero, and foreign has an index value of one. So, now, if you wanted to access the first value, then you can access it using index zero. Now, in the line of code that stores the value of TransferType.Domestic into the variable X, we will get an error. We have to explicitly convert this to uint8 and then store in the variable X. For invoking functions that require enumeration as argument, we will need to provide an integer index value. Now, let’s look at a sample contract to understand enums better. Now, the sample contract that we have on the screen is called contract EnumContract. Again, remember, contract see lower, and then we have the name of the contract, you always try to use the capital letter for the first letter of the contract name. In this contract, what we are doing in the global space, we are creating enum, and the name of the enum is names, and then within curly brackets, we are having four values, Joe, Brandy, Rachna, and Jessica. So, there are four values inside. So, that means this is going to have index zero, one, two, and three. Now, like I mentioned and showed that to you in the last slide, we just cannot get the values of zero, one, and two, we have to convert it explicitly. So, if you see in this function, we are getting an argument, and so what we’re doing is that we are getting an argument saying that we want to see what the value is at that specific index. So, we’re getting an argument that’s probably going to be anywhere between zero to three, and now it returns a string. We’re going to look up this enum based upon the argument that return the value. So, what we’re doing is that we’re comparing the argument, we’re converting it explicitly. So, for example, names.Joe. That converge to zero and then so the argument is zero, then the returning Joe. Now, if the argument is one, in that case, we’re getting names.Brandy, and then we’re returning Brandy, and then that’s how it goes. So, in fact, I’m going to show you in the side of my screen and see how this works. So, let’s go deploy this contract. So, again, I’m using mainly remix editor, we’re going to go deploy this contract, and I’m in the JavaScript virtual machine that is in browser network that is running in my browser right now. So, I’m going to deploy this contract. Once you deploy this contract, you can click on this lower part. Okay. So, if you see, these are the specific values. So, now, we have this function getNames. Let me zoom in just a little bit so you can see a little bit better. Okay. So, I’m going to pass in. Let’s try passing an argument zero and then click on the function name. So, it gives me Joe back. So, if we see, the first element was zero, the first value is zero. So, now, let’s try passing three, and we get a value of Jessica. So, that is how enums work in solidity. Pretty simple. All they are is custom type that you’re creating with values inside it.

12. C4L3 Concept 12 Structs V2-eSTO3TLakIs.en

In this concept, I will explain you another complex data type called struct. Struct is a user-defined type declared by using the keyword struct. In this code example that you see on your screen, we are creating a struct called CarType. This struct CarType has four members: name, model, owner, and price. Like I mentioned, structs are just user-defined types. Now, we can create variables of type CarType. Also, structs cannot have members of its own type. Structs can be contained in arrays and mapping. So, that means you can definitely create an array that can hold struct types, or you can also create a mapping that can hold struct values. Now, structs are not a part of the ABI definition. What that means is that the color of the contract when looking at the ABI will not know if structs are defined in the contract. External function calls, that means calls made from outside the EVM, cannot send or receive struct types, but calls made from within the EVM, from one contract to another contract can send and receive struct types. Now, let’s look at sample contract that uses struct so we can understand the concept of struct a little better. So, now this code example that we see on the screen, again, starts with the pragma line. Then, we have contract. The name of the contract is called strokes contract. Now, in the very beginning, I’m creating a struct called Family. Now, this has three members: lastName, houseNumber, and age. So, bytes32 lastName. I’ll explain to you why I wanted to use bytes32 because we’re going to search on the struct and we cannot search or work with strings, or compare strings. So, that’s the reason we’re going to use bytes32. Now, that’s a very normal thing that you’ll see in contracts is using bytes32 when you’re looking to compare strings. We’ll get to that in just a second. So, we have three struct members here. Then, we’re creating an array. So, we’re creating an array of type Family. So, like I said, this is just a type. Now, we have to create either a data type or of course, in this case, we’re creating an array. Now, this array is going to store these structs. The name of the array is called myFamily. Now, what we’re trying to do is we’re trying to get names. So, what we’re trying to do is someone is going to pass this saying they want to look up the struct or this array and see if this name exists in it. The way we do that is we’re going to get the name in bytes32. Then, we’re returning the complete value, that is, as a part of the struct, so three members. We’re returning the lastName, houseNo, and age. So, we’re going to loop over this array that we just created, myFamily. Now, if you receive a looping over the array myFamily.length, whatever the number of people that we have in this array, it’s going to loop over that. Then, we’re comparing our input argument to the last name and seeing if it matches. So, now, since I mentioned, we cannot compare strings like this. So, Solidity just does not support comparing strings in this way, and that’s the reason we are using bytes32 because we can definitely compare bytes32. We’re comparing our input argument to the last name and looping all throughout the array, whenever that matches. Now, returning the struct information or the array-specific index. We’re doing myFamily index i returning the lastName, myFamily again, index i returning the houseNo, myFamily index i returning the age. So returning the information. The second function that we have, addName function, I wanted to show you. Now, structs cannot be passed as arguments, so we are passing all elements and attributes of struct as arguments. So, you cannot just pass a complete struct as an argument. That’s the reason we add- if we need to add a different name to our struct array that we just created, we’re going to have to pass it as separate argument. So, we’re getting again, bytes32 lastName, value, and age. Then, we are creating a struct in memory inside. We are storing, and the way you store using only access struct members is using the.notation. So, we just created an empty struct here in memory, and now we’re going to add all these different input parameters to end the arguments that we received. So, we’re going to say newFamily.lastName is equal to our input or argument, lastName, newFamily.houseNo and equal to value that we just received, and newFamily.age equal to the value that we just received. Now, we’re going to push it. So remember, we have an array here of this type. Once we’ve created our struct here, we’re going to push this new information, this new type into array. The newFamily is array. So, we’re going to say myFamily.push(newFamily), and then that’s it. So, this is how structs work. Again, I would definitely encourage you didn’t copy this piece of code from our GitHub page and play around with it, so that you really get comfortable with how structs work in Solidity.

13. C4L3 Concept 13 Global Variables V2-i602N_bcdBQ.en

In this concept, we will learn about the most commonly used global variables in Solidity. We will learn about Block, Message, and tx global variables. We will also show you how to carry out the Ether Unit conversions and Time Unit conversions using suffixes, Ether, and time. Let’s get started. So, we will start with the very first global variable called block. You can get information about a specific block using the block global variable. This has a bunch of methods that you can call. Like number, returns the current blocks number, Coinbase to get the address of the current blocks minor, difficulty, to get the current blocks difficulty, gas limit, just as the name says the gas limit for the current block, timestamp is the same as a block time, Block Hash, the hash of the block number that you provide. If you use it for the current block, you will get all zeros, because there is no hash for the current block because it is not mind yet. Let’s move on to the next global variable called Msg, a very important one. In fact, you would end up using it many times in your contracts. This gives information on the current transaction that is being executed. Msg.data, gives us the call data in bytes. Msg.sender is the external link on account or another account that sends this transaction. Msg.sig is used to get the signature which is the four bytes of the call data, the first four bytes of the call data, the signature. Msg.value is a very important one that is used to check amount of wei sent along with this transaction. Now, this is of course only going to be available in functions that are marked payable. Let’s talk about the next global variable called tx. tx.gasprice is a price paid for gas for this transaction. tx.origin is the address that originated this transaction. tx.origin is different than msg.sender that we just learned in the last line. In case you have two contracts, A and B, for contract A, the msg.sender is the external accounts address, and so is the tx.origin. But for contract B, the msg.sender is contract A’s address, but tx.origin is externally accounts address like you see in the diagram on your screen. Let’s now talk about the next global variable, Ether. Ether, the main unit for Ethereum has multiple denominations like wei, finney, and many more. You can use suffixes in Solidity to convert from one denomination to another. There are many online websites that you can visit to convert from one denomination to another, and you see a screenshot on the screen right now of one of the websites. Now, let’s look on the screen that you have. In the very first line of code, you are evaluating wei to a specific denomination of ether, and then setting the flag accordingly. Now, this is easily possible since you can convert from one denomination to another. All you have to do is use the word wei or ether. Finney is another denomination of ether, and there are many other denominations too. Also wanted to mention that wei is the smallest denomination of Ether. Now, let’s look at another global variable in Solidity called now. Now returns block time in seconds since 1970. Just like ether, you can convert time using suffixes. Let us see all this now using an example code. Let’s look some sample contract for this global variables so you have a better understanding and how all these work. So, now we see a contract on your screen called contract GlobalsContract. Again, I’m going to keep reminding every time, start with pragma line, Solidity, version of Solidity, and contract word c. Normally, by convention, the name of the contract starts with a capital, and that’s just a convention, and then within this we have the whole contract. Now, what I’m doing, I’m actually having a variable or a storage variable if you see string type, public visibility called lastCaller, and I’m just storing a value saying, not setting it yet. So, that’s the value originating it with. Now, we have a couple of functions. Let’s walk through the first function here. Now, the first function is going to show you how ether sub-denominations work in Solidity. So, the function is called etherUnitsTest() public pure. We will talk about visibilities. For now just go with the flow, but we are going to talk about all these different things that you see on the screen, public pure in our functions concept. This is returning a bool value. Now, what I am doing is that I’m actually comparing if one ether equal 2,000 finney. If that is the case, I’m going to return value, which is value is being set to true in this case. So, we’re returning a true, if this is equal to this. If you see, that’s how we can work from one denomination do another denomination, just write the word after the numeric number and it’s going to convert it for you. Now, let’s look at another function that demonstrates the use of Time Units, function called Time Unit. Again, public view, we will talk about all these in our functions concept. So, what I’m doing here in this function, I’m actually setting a variable, you would time, called time now to now. Remember, this is storing the time that has passed, the block time in seconds since 1970. In fact, this is 1970. Let’s change that. Not 1960. Now, time now, so what it’s doing it’s comparing time now equal to 1,000 days. So, again that is how you again convert it. Remember this time is in seconds, because it returns in seconds. So, we can compare from seconds, convert this days, so we can easily compare from one denomination to another denomination using that suffix space and then it’s returning. So, what it’s doing, it’s comparing if time now equal to 1,000 days, which not the case, so I am going to show you so. This function is going to return false for you. Now, moving on, let’s talk about the next global variable we talked about called block. So, this function demonstrates the use of block object. So, if you have a function called get block information and now it’s returning all these numbers. It’s returning the number of the block, the hash of the block, the Coinbase, and the difficulty. So, the way we access it, all we do is block. Now, these are global variables, you don’t have to import them. They’re just available in the contract for you to use. So, we’re storing this block net number in number, we’re storing into hash, we’re storing into coin, difficulty, and then returning them. The last function over here shows how Msg works, the fourth global variable that we just talked about in our slides. So, this function is called getMsgInformation is returning data, signature, and the sender. So, it’s returning msg.data. Remember that it returns the data of the current block, signature, and the sender. So, now let’s go and deploy. I’m going to show you a couple of interesting things here, just so that, I think the more you play with remix and all these contracts, the better understanding you will get, so let’s go to Run tab, Compile tab has already compiled. So, let’s go Run tab and I’m going to delete this instance and now let’s deploy it. So, once you deploy the contract, you can click on this. Now again, I wanted to show, you can anytime you create instances of the contract, you can always delete them, so you can start with a brand new one. I’m going to do that again just so that I can show you that. So, let’s deploy it again. So again, if you see I’m using my JavaScript VM, which is my in-browser Ethereum network running right now, and the address is this, which means what is my msg.sender going to be? This address. So, we’ll confirm that using the function calls that we have. So, let’s go deploy it. Let’s look at the functions so if you see we have all these functions described here. So, let’s look at the first function. So, the first function is, it’s comparing if one ether is equal to this much finney, and if that’s true is going to return a true. All right. So, let’s run that function, see it returns true. Good. So, that’s working. Now, let’s move on to the next function. It’s going to compare that if it’s time now equal to 1,000 days, which I’m suspecting it should see false. So, let’s go look at the time now function, Time Units. So, it’s returning a zero, because we never said the value of U, and so that means of course it’s going to be zero, and return time now that’s going to happen. Then, getBlockInformation is, let’s go and click getBlockInformation, but if you see it’s going to turn the number of the block, hash of the block, coinbase, and difficulty. So, let’s get the block information, see if you see all this information, block number. This and this all this information is sending being sent out to you. If you also see remember, I showed if you look at the block hash of the current block is going to be giving me a zero, and that’s the reason I’m using block hash of number minus one, so I get my block number, store it in the variable number, and the number of return I get from minus one, so it didn’t get a zero. So, that’s the hash of the previous block that was just minding. The last function here at getMsgInformation. That’s the interesting one, I wanted to show you that. Let’s go and look at our getMsg function, let’s called that. So, that’s the data, of course I didn’t send any data along with you, this function call right now. So, it’s going to pick up information from there, and sender, that’s the important one I definitely wanted to show you. If you look at this address msg.sender 0147 on your screen, and this is the address on my screen right now. So, that means I’m the one that’s originating the contract or initiating the contract right now, so it matches. So, a couple of things, interesting information again, copy this code from our GitHub page, play around with it, so you get really comfortable with the way global variables work in Solidity.

14. C4L3 Concept 14 Functions Part1 V2-hZVHqJ5oiEM.en

In this concept, we will learn about functions. Solidity supports functions, just like other languages. A basic syntax of function declaration looks like this. If you look on the screen, we have the keyword function, followed by the function name, and then any arguments passed, followed by function type. Now, you can have many function types here. We will talk about this in our next slide. Then, if there is a return value, we will save returns, and then in bracket the return value, or the type of return, that you’re trying to make from this function. Then, we have out our curly braces, and the function definition inside it. So, this is what a typical function statement would look like. Now, let’s talk about various function types now. So, the very first one that you see on this chart, on the screen is a public. So, public means anyone with an Ethereum account can call this function. It is visible to everyone, it will be a part of the ABI, the application binary interface. So, that means anyone can call this function, it will be visible to everyone who has an Ethereum account. Now, public and private really don’t imply security too much, it is more for the programmers, to imply that this function can be called or not. For example, helper functions could be made private. Private functions are not even available in the derived contracts. So, they’re not available, there only available inside this contract. So, like I said, if there are helper functions that you want to call one function from another function, and they have absolutely no other purpose, make them private. The next visibility that we wanted, or the function type we wanted to talk about, is view or constant. Now, this specifies that the function cannot modify contracts data. Now, interchangeable names, I mostly see view, but you might see contracts that’s a constant. So, I just wanted to let you know but view is good enough. So, it specifies that the function cannot modify contracts data. So, if you have a function that is not changing any state or modifying any data, only looking at some data, then you should provide the word keyword view here. Pure, means that you cannot modify nor you can view contracts data. Payable, this keyword means that whenever some outside source, or some outside entity like you or me attempts to call this function, we might call or try to call it and send money along with this function call. Now, this next slide on your screen that you see, explains you four different visibility types. So, we talked about function types, now this information overlaps but again, definitely wanted to show you the visibility separately. So, we have four visibility types in Solidity; public, private, internal, and external. Again, I wanted to mention that these visibilities apply to functions, and variables too. External function types. External functions are part of the contract interface, which means they can be called from other contracts, and via transactions. External function cannot be called internally, like a normal function call, you can call it using this keyword. Internal functions, what are they? Internal functions and state variables can only be accessed internally, that is from within the contract or contract deriving from it without using this keyword. In Solidity, a function may be called from within the contract, or from outside the contract, or even other outside applications. So, the internal function calls are encoded by compiler as cold jumps. Calls made from outside contracts, or outside applications, use the EVM message call for function invocations. So, we just talked about public and private visibilities in a previous slide. So, you know what those means. Again, a public visibility means that anyone with an Ethereum account can call this function. It is visible to everyone. It will be a part of the ABI. Private functions are only visible from within this contract, not even from the derived contracts. They restrict the visibility to only the compiler, you can set the visibility to internal. They restrict the visibility only through EVM. So, that means other contracts cannot call this function. You can set the visibility to external. We can also set the visibility of storage variables to be internal, if you want it to be available only from this contract, and also from derived contracts. Storage variables cannot be declared external, since they are stored with the contract. So, again, important piece of information, you cannot make storage variables external, because they are stored with the contract, so that means you should be able to call them. Okay. Moving on. So, by default, a function is public unless specified differently. So, if you forget to specify public, of course the compiler will give you a warning, but it’s still going to initiate the contract, and the contract will be public, unless you specify differently. So, again, important information is that Solidity automatically creates getter functions, if you create a public storage variables. So, if you have variables that you like to look on the screen, for example, so if you’re doing something like string ownerName, line of code. So, if you have a line of code that says string ownerName, we are creating a variable ownerName, but not making it public, so no getter function will be created. But if you say string public ownerName, we are making it public, a getter function will be created automatically. Same name as the name of the variable, in this case, a function will be created, the name of the function would be ownerName. Part of information, functions can have multiple return values. So, when a function returns multiple values to an outside application, the result is returned as an array of values. Impart an information again remember, if there are multiple return values to an outside application, the result is going to be returned as an array of values. Now, Solidity does support function overloading. What that means is that, you can have more than one function, with the same name, as long as input parameters are different. So, Solidity does support function overloading. Let us summarize functions. An automatic getter function is created with the same name as a public variable, for public storage names, variables. A public function can be called from inside the contract, and also from external sources. A private function can only be called from within this contract, not even from the derived contracts. External functions can only be called from the outside application, but from within the contract, we will have to use the word this. So, this operator would be used for those kind of function calls. Internal functions can only be called from within the contract, and also from derived contract, but not from outside applications at all.

15. C4L3 Concept 15 Exceptions V2-msB6YeUNQxk.en

In this concept, we will learn about error handling in Solidity. Every programming language needs to implement some kind of error handling. We will learn how to throw exceptions using revert(), require(condition), and assert(condition). There are two types of errors in general, the first type are the run-time errors due to some EVM or operations error, the second type are the application errors. Now, these are throne due to some condition in the code or some wrong data. Now, how do we handle errors. This is totally based upon the developer of the contract, who can decide how to communicate this error back to the caller of the contract? The contract can either return a value to the caller to communicate the error or the contract can emit events to relate the error. It could also be combination of returning a value and also emitting events. Or of course the preferred way is to throw an exception. In this concept, we will learn about throwing exceptions back. Moving on, one thing I wanted to mention is that Solidity does not support Try-Catch mechanism. This means that once an exception is thrown it will just be passed over to the caller. When the contract code throws an exception it leads to rolling back of all the changes that happened in that transaction before the exception was thrown. Know ethers are sent. All the set ethers are also sent back. Gas is used, which means that any gas that was used prior to throwing the exception the caller will still have to pay for that gas. One another important thing I wanted to mention, that even though this transaction was unsuccessful, it will still get recorded on the Blockchain. In Solidity exceptions are thrown using the revert function, let’s talk about that. Once an exception is thrown, the contract execution will stop and the exception is propagated all the way back to the caller. Also, all unused gas will be sent back. Now, there used to be a throw statement but that is deprecated in solidity, now, sent a true statement is used, it uses up all the gas that is sent in the transaction call, so avoid using true statements. There are two additional global functions that can be used to to exceptions, require(condition) and Assert(condition). Both these functions take conditional expressions as their arguments, if the condition is not met, that is, it leads to a false, an exception will be thrown. Require throws revert like exceptions, which means all used gas is sent back, whereas, assert throws through like exceptions where all the gases used up. Assert is mostly used for internal testing, require is mostly used for throwing exceptions back to the caller. So, if the Boolean expression returns to be a false, then the entire function is immediately exited and no changes are made to the contract at all. Now, this is a great way to make sure that some condition is met before the function is executed. Like in the first example that you see on the screen, we are checking if the msg.sender is the owner of the contract, only then the function will be executed or an exception will be thrown back to the caller. In the second example we are checking if the msg.value sent along the transaction call is greater than 0.1 ether, only then proceed otherwise, throw an exception. Now, let’s look at a simple contract that implements error handling so we can get a little bit better understanding on how error handling works in Solidity. Okay, so we have a sample contract here, and the name of the contract is exceptionContract starts with the keyword contract. Now, if you see we are having a public variable here called lastCaller and we’re just setting a value of none to it that is it. Is a public variable string type lastCaller, setting a value to none. Then, we have a function called a revertBehavior. Now, this function takes in a name of as an argument and sets the lastCaller variable to this argument received. So, whatever the argument we’re passing in the function we’re setting the lastCaller to that variable or the argument that’s received in. Now, what we’re trying to do in this function is also, since remember we do not have a.length property and strings, so we’re converting it in bytes, by using this conversion. If you remember from the concept we’re taking a name, putting into brackets, enclosing with the word bytes, and then checking the length of that. If the length comes to be zero we’re reverting or throwing an exception. So, all it’s doing is that, if someone sends as an empty argument but some kind of argument but an empty, there’s nothing in the strings it’s going to throw an exception. Okay, and also wanted to mention is that there’s another way of doing it using the require statement. I’m just going to show you both here and I can always uncomment it but we’re already doing it that’s the reason I have commented, so this works perfectly fine too. So, we can replace this whole line of code, this value, this value, and just check this. Okay, so what we can do is we’re converting, we’re just saying require condition inside the brackets, we’re checking if this length is greater than zero, then you can just return true. So, same things so either you can use a revert kind of thing, where you’re doing something here or you can just throw an exception right before you’ve done anything yet. Also wanted to mention is that in this case, we’re setting the value of this. So, remember when I talked about and I explained that to you that anytime you throw a revert all the changes will revert back, so that is what is going on in the first revert behavior function, the lastCaller is being changed to the input argument and then an exception is thrown after that. If an exception is thrown the last quarter reverts back to its original value does nullifying defect. So, let’s now look at how this works, I’m going to deploy this contract. Once we deployed this contract, now let’s pull it down and see what we have, so as of now lastCaller is nothing, so we’re just going to call the value and set to none. Got it? Now, we’re going to call the function, let’s give it a value “Udacity”. Then, we call this function. Okay? Now, once we call this function, if you see this is not going to return true, that means that exception will not be thrown in this case because this condition is not met here, so if I call the lastCaller function now it’s set to this value if you Udacity. Now, let’s call this function again with an empty string. So, remember any time you pass arguments here string type you have to use double quotes because it is expecting JSON. So, revert and now I’m going to call the function again, okay. So, now if you see it sets the value of this right here, so it should be empty strings but now towards an exception. Okay. It’s still the same, what it did, it set it to empty strings and after that it checks if its value equal to zero and it’s going revert. So, to roll it back to initial value of Udacity even if it was changed right here. So, that is how exceptions work, you can use require, you can use revert. So, again play around with this piece of code and get comfortable with how exceptions are thrown and Solidity.

16. C4L3 Concept 16 Inheritance V2-d1EjY4UeJM0.en

In this concept, we will learn about inheritance in Solidity. Now, Solidity supports abstract classes. It also supports multiple inheritance. Contracts can inherit from multiple contracts. When a contract inherits from multiple contracts, only a single contract is created on the block chain. This is the last contract in the Solidity file. The code from all the baseContracts is copied to the derived contract. Solidity also has the concept of interfaces. Interfaces are created using the keyword interface. Interfaces cannot have any variable declarations, there can only be function declarations, but no function body. So the function getValue public returns bool, the one that you see on the screen ends with a semicolon, there is absolutely no function body. It is the responsibility of the derived contracts to make sure that all these functions are defined with a function body. This is how in fact token standards are also implemented. Token standards are like an interface. If any contract, that once we adopt a token standard, it needs to now implement these functions that are declared in the interface standard. So we have token into places like ERC 20, ERC 721, and of course, some more. Now, let’s look at the code on your screen. In this example, you will find a contract named account, and then we have a derived contract called credit account that inherits from the contract account. The way you inherit from an account, you use the word is, the keyword is contract, so you say contract CreditAccount is Account. In this case, the credit account will get deployed to the network since it is a last contract in the file. The baseContract does not need to be in the same file. You can import contracts from other files or even online links or even from GitHub. We can use import statements for this purpose like you see on the screen. In this example, we are importing the file Account.sol from a local drive. Now, let’s look at a sample contract to understand inheritance better. So, let’s look at a sample contract that we have on this screen here. So, we have a contract called mainContract, nothing really happening in this contract too much, so we have a variable that we’re declaring of uint type it’s internal, and value is the name of the variable and then we have a constructor function and then we have just two functions, deposit and withdraw. So that’s how you have a simple contract. Now, we are going to import this contracts, so the name of this file is main contract. Now, let’s go back to another contract which is inheritance contract. We’re importing this contract, now we are in the same drive so the path is simple, but you could import it from online or even from a GitHub page. So, import this contract, and now inside this contact we’re actually creating another interface. So, we have an interfaceContract that has a function, sendMoney, but there is no function body. So, if you look functions sendMoney, it has input parameters, external returns bool, that’s it. There’s no function body, no brackets, just a semicolon. This is how you define interfaces. There can be no variable declarations inside the interface, just basic function values. Now it is, of course, the work or the load that comes upon the inherited contracts that have to make sure that they implement these functions. Now, let’s look at another baseContract here. This is a baseContract that has it’s constructor, deposit and also withdraw function. So baseContract, we have another constructor function and the deposit function right there. So we have two contracts in this file so far, interfaceContract and the baseContract. Now, we have another contract that is showing multiple inheritance. Remember, I said you can always inherit from multiple files or multiple contracts. So now myContract, I’m actually getting it inheriting three different contracts. So, baseContract, interfaceContract, and also the main contractor. It’s inheriting this interfaceContract, it’s inheriting this baseContract, and the mainContract that was in a separate file because we’ve imported that file. Now again, I wanted to mention, if you see these numbers, and the way we have to do this because we’re inheriting it. So, these contracts, how to construct a function, we need to send the arguments, if you don’t send arguments right here, our compiler will not let us deploy. So, let me show an example. So, if I delete this argument right there and I try to deploy this myContract now, it’s going to say it cannot do that. So, if I say, let’s give it some input parameters and then if I deploy it, it’s going to give an error saying it does not implement all the functions, all that means is that we cannot deploy, we have to get past the arguments of all the contracts that it’s inheriting from right there. So again, this shows multiple inheritance, three different contract files, two are in the same file, one is coming from a different file. One is an interfaceContract, if you see my interfaceContract, I have a function sendMoney, now this has to be differently implemented since if it is unimplemented, it’s not going to let you deploy this contract. It’s going to say you can I deploy this contract because all the functions that it’s inheriting from the interfaceContract have to be present. So, we are in fact defining this function, the sendMoney, there was just, if you see this function, it gives you what it should look like, but it’s your responsibility to make sure that this function gets implemented and defined in your derived contract. So, you still have this function. Again, a simple way you really don’t have to focus on the code for now, what it’s doing, just a simple way to show how inheritance works in Solidity. Let’s go deploy it and see what it looks like. So when you have this option, it gives you a drop down option, you can deploy mainContract, myContract interfaceContract. Again, it’s not going to let you deploy interface, let me show you that. So, since interfaceContracts are just an interface, there are no function bodies, you cannot even deploy them. So, if I say deploy, it’s going to not make you deploy it. It’s again saying that the contract does not implement all the functions and thus can not be created, so it’s not going to let you deploy that contract. Now let’s deploy our baseContract. Let’s try deploying our baseContract right here. So, if you see this contract is just a simple contract, it’s expecting an input value. So, let me start with an initial value of a 100 and deploy this contract. So, now we have two functions and of course, the value because it’s declared public, and now if you get the value right now it’s going to be 100 because that’s what we pass through a constructor function, now let’s deposit in another amount of 20. Deposit, now the value is going to change to 120. If I take out 50, and then I withdraw, now let’s get the value, it’s going to be 70, so it’s working fine. So, now I’m going to delete this copy of this contract and deploy the very last one that’s inheriting from all these different three contracts. So, let’s deploy a myContract now. So let’s go back here, go to on myContract and this is expecting. We’re already passing our arguments for these contracts right here but of course, it expects this also has it’s own constructor function expecting a string, name of the contract, and I’m going to just call it Udacity. Well, let’s deploy this contract right there. All the functions, so deposit, sendMoney. So if you see these functions and not a defined on myContract, but since I’m inheriting it, all these functions end up in a list of these functions because that is how inheritance works. So, you can deposit, you can withdraw, you can get the contract name, you can getValue, and if they were set to 100, all these functions work, and perfect. This is how inheritance works, I definitely want you to get these two files from our GitHub page, play around and see how comfortable you get with inheritance in Solidity.

17. C4L3 Concept 17 Events V2-rmndEiHAkjE.en

In this concept, we will learn about events in solidity. When a caller sends a transaction to a contract, the state of the contract changes. Now, as a developer, we can program our contract to emit events when its state changes. We can write a DApp which stands for a decentralized application to watch for these events. Events are written using the keyword event. Events do get stored on the network. Now, events are a part of the ABI definition. What that means is that anyone looking at the ABI of a contract can tell which events the contract is emitting so a DApp can be written accordingly. Events needs to be declared before they are emitted in a function. So we always declare events then we write functions. Event declaration looks like a function without a body and also ends in a semicolon. Events are invoked just like you would normal functions. Now, let’s look at a smart contract example that implements events. So, this is a sample smart contract that is emitting events. In fact I’ve also included since you’ve learned quite a bit about solidity now. So I’ve included strokes in it, I’ve also included modifiers in it, constructors, msg.value or the global variables. I would definitely encourage you to get this file from our GitHub page and look at it and play around with it and then really get comfortable with how all these things work and kind of bring everything altogether. So, name of the contract. With the word contract, starts with events contract, name of the contract. Now we’re creating if you remember, now is a global variable that gives us the time in seconds since 1970. Now we want this bidding to end in five days. So we’re kind of declaring an argument here saying bidding ends and it says now in five days, okay? Then we’re creating a struct which is high bidder. It has the address of the person who’s bidding. Of course the address comes from this part and then we have the name of the bidder and then the bid that the person is placing on. So that’s a struct. Now we are creating a variable of type high bidder. So high bidder public high bidder, okay? Now again, since this was a struct which is just a user-defined type, we’re supposed to create variables of this if you want to do anything with this. We’re creating a variable of type this and now this also is emitting two events, high bid and a low bid event or a bid failed event, okay? So if anyone bids higher and I’ll show you in just a second what it is but typically it’s an event with the word event, name of the event, arguments, and a semicolon. So, kind of like a function but nobody ends with a semicolon and we have another event, event keyword, bid failed, arguments, and a semicolon. Remember we have events always before a function so we have events initially that we are declaring here in the file and then we have a modifier. What this modifier is checking if it has not crossed the time. So remember we set our bidding ends in five days so we’re checking if now is less than bidding ends, okay? Continue. Else throw an exception. So, if this time would be after five days, after I deploy the contract, then of course no one can bid on it and it’s going to throw an exception so that’s a modifier and if you look an up function, we’re applying this modified time. So, this is the name of the modifier coming from there and there are initial constructor. When we start the bidding, I want to kind of set up an initial value. So we can start initial values here. So we’re starting the bidding at one ether saying this is a high bid, okay? So, we’re going to set our high bidder. Remember, that’s a struct type variable and I’m setting the bid initially to one ether. Now in the function bid, first of all look at this word payable. Payable since ether should be coming along, okay? So if you don’t send either, it’s going to send you o or to give you o, exception gives you an exception. So, time, because we want it to end in five days from now. So and then we’re also giving the name of the bidder. Whoever bids, wants to give their name initially who’s bidding and the value of course comes from this value. So whatever comes along comes from this value and now we’re checking for msg.value. Remember MSG is a global variable. You can get the value that’s coming along using msg.value. We’re checking if this is higher than the initial bid that was set, okay? So we’re setting it to one ether initially. We’re checking if this value comes higher than that value. If, proceed. If not, revert to an exception, okay? You can also emit an event right there. So if you have a front-end application watching for this, you can see bid failed event has been issued, or here high bid event has been given right there. So, you can emit events just this way. We have the events declared here but this is how you emit events, word event or you can emit events just this way, okay, with the word emit and then the name of the event that you’re sending and then that one, argument values right there. So, in this function if you see we’re checking the value and if the high bid that the receiving value is greater than the bit that we already have, then we’re going to accept the bid and we emit an event and at the same time let’s store it? How do we store it? Since it’s a struct, right? So, highBidder.bidder using the dot notation, msg.sender. So message our sender, the person who is sending the value. So, his address is getting stored because we need to get the address type and then the name of the bidder and then the value. So, we’re setting all these values bidder name and that. So let’s try now deploying this contract and I’m going show you. In fact I’m also going show you how exception that thrown in. So let’s deploy this contract, events contract and using this address, let’s deploy this contract and let’s go. So, if you see, we have the contract deployed. So, for now, high bidder is going to be, initially that was set, okay? That’s it. So there’s nothing set as of now. So now let’s go bid on it. So I’m going to go bid on it saying something, I’ll give Udacity, okay? So we’re bidding on it. Now, I’m not going to give a value here, okay? So let’s see. So remember if there is no value coming along, it’s going to throw us an exception and I’ll show you how exceptions are thrown. So let’s look on this bottom screen. So, if I send in a bid but no value is given, no ether is being set along since remember this is a payable function. It is expecting ether. It’s going to throw an exception. So let’s bid on it. See, there’s an exception. Since it’s reverted exception, the transaction has been reverted to the initial states. If you look on the bottom of the screen, you’ll see that the transaction has been reverted because it was wrong. Now let’s set a value that’s lesser than one ether. We’re again going to get exception remember. So this gives an exception inside the function if the value is lesser. So let’s send it a value of just one ether. Remember that its expecting greater values. Its expecting a value greater than one ether because it has to be greater, okay? So let’s send again and look at our screen. So, let’s go to the bottom of our screen. I’m going to clear the screen so you guys can see it better. So, I’m going to again send it a bid with that value and again it says reverted. It doesn’t go through because my bid is not as expected. So now let’s go again. Now this time I’m actually going to send a value more than one. So, if you see this is my denomination ether. I can choose different denominations from there. I’m going to choose 1.1 ether. Now, I’m expecting this will go fine, right? Because I’m higher than the initial bid that was one ether. So now let’s clear the screen so you all can see it better. I’m going to send a value of 1.1, now it goes through. Perfect. So now if I get the high bidder information, it’s changed. My name came through, my address came from this address that I’m sending the bid from and it also gives the way of course everything is way on the screen. It gives us a value of how much came along. So, this is how you have everything coming along. So this contract shows a bidding contract that’s going on and it has implemented structs in it, events in it, modifiers in it, constructors in it and also events in it. So, definitely make sure that you look at this file. This is how it emit events and your front-end application can watch for this event and act accordingly. So, get this code from our GitHub page and play around with it and get comfortable with how all these things come together in solidity.

18. C4L3 Concept 18 What Is A Token V3-eU9CnNPyPiU.en

In this concept, we will learn about what are tokens and how to create tokens on a blockchain network. Now, to understand tokens, we need to understand what are token contracts. Essentially, a token contract is a smart contract that contains a mapping of account addresses and their balances. The balance can represent anything of value not just necessarily Ether. It will represent a value that is defined by the contract creator. So, balances can be used to represent physical objects or monetary value or some kind of license or any other asset. The unit of this balance is commonly called a token. Once you write a token contract, then it gets deployed on the network. These token contracts have some standards that need to be followed to be a standardized token. ERC stands for Ethereum Request for Comments. Now, these are technical documents that are used by smart contract developers at Ethereum. They define a set of rules required to implement the tokens for the theorem ecosystem. It makes standardization easy since everyone knows what functions the token contract will have.

19. C4L3 Concept 19 Token Standards V2-26-UA044P9s.en

In this concept, let’s talk about some of the famous ERC standards. We have ERC-20, ERC-223, ERC-721, and then ERC-621, and also ERC-827. ERC-20, this is the most common and well-known standard with an all crypto community, more than 90 percent if not all issued ICO tokens on deuterium implement the standard. The key benefit is standardization, any application or other smart contract can interact with the token in a standard manner without a need of knowing other details about the token. Therefore, we have a very pleasant way to create any ICO token, and have a standard way to interact with all of them, like they are all the same. All the application will need to know the deuterium token address that implements the standard because the functions are predefined. ERC-20 has many benefits including allowing wallets to provide token balances for a 100 of different tokens in a very standardized way, and also to be able to transfer tokens from one address to another address. I also wanted to mention that it is used to create fungible tokens, what that means is that all tokens are same. So, every token created by this contract could be exchangeable with another token. Next, let’s talk about ERC-223. Now, this is a proposal that was introduced by a developer who decided to solve issues with the current ERC-20 standard for tokens. Advantages, it provides the possibility of avoiding accidentally last tokens inside contracts that are not designed to work with sent tokens. However, these accidental transfers, which are uncommon already, will probably become even more uncommon with ENS that stands for Ethereum Name Service in future. Now, ERC-223 transferred to contracts, consumes less gas than ERC-20, so that’s an advantage. Disadvantages, ERC-223 is a proposal right now, not a standard, therefore, there are none of the high-profile ICO tokens that use the standard. Also, it is not yet implemented in any of the production tokens that I found from my research. Exchanges might need to do some special modifications in order to support such tokens. There are options that some of the exchanges might not be prepared for this yet. Now, this standard also creates fungible tokens, so all tokens have the same value. Moving on, let’s talk about ERC-621. ERC-621 is just an extension of ERC-20 token standard. It adds two additional functions: increase supply and decrease supply. Now, we will talk about all the functions when we get to ERC-20, so you will understand a little bit better, but again just to recap ERC-621 adds two additional functions, increase supply and decrease supply. This increase and decrease the token supply in circulation. We will talk about token supply more in detail very soon. ERC-20 only allows a single token issuance event, this restrict the supply to certain amount which can’t be changed. ERC-621 proposes that total supply can be modified. Let’s talk about ERC-827. This is one of the latest token standards. It is an improvement to the standard interface ERC-20, with method that allow the execution of calls inside transfer and approvals. This standard provides basic functionality to transfer tokens as well as allow tokens to be approved, so they can be spent by another on-chain third party. It also allows to execute calls on transfers and approvals. This extension of the ERC-20 interface allows any tokens on deuterium to be reused by other applications from wallet to even decentralized exchanges. The ERC-20 tokens standard is widely accepted, but it only allows the transfer of value with ERC-827, deuterium users are available to transfer value and data, both on transactions. Let’s talk about ERC-721, the goal of this proposal is to create a non-fungible token. In ERC-20 and ERC-223 standards, they have a supply of tokens, the tokens are fungible, what that means is that single unit of that token is equal to any other unit. This makes it easy to treat those tokens as all of the tokens supply can be treated in the same manner. However, there are various cases where you need to have an identical tokens, which are used within the platform, and add some extra parameters and price them differently. For instance, we could have a token which represents some part of the real estate object, and each token might have some different parameters added to it. The famous CryptoKitties is an ERC-721 token. Now such a standard makes it easy to create marketplaces for multiple non-fungible tokens.

20. C4L3 Concept 20 ERC Walkthrough Part 1 V2-kBLVjENeXcQ.en

Let’s focus on the ERC-20 token standard. This is the best one to understand to really understand how tokens work. So, we will focus on this standard and then finally, I will show you how to create your own token, and then deploy it, and also give it to your friends. An ERC-20 token standard or a contract is defined by the contract’s address and the total supply of tokens available to it. To create an ERC-20 compliant token, we need to implement certain functions and events that are described by the ERC-20 specifications. So, we have three optional fields, six functions, and two events. The first three optional items, they’re usually provided to provide more detail to the public. These are the tokens name, its symbol, and the number of decimals. Let’s talk about all these fields in detail now. So, we’re looking at a sample, an ERC-20 interface contract what an interface would look like. So, let’s start from the very first one, the name. The string public constant name that says Udacity Token. Now, these are all the first three are all optional items. The name of the token contract is the long name. So, this name is the long name by which the token contract should be known, for example, Udacity Token. There are no restrictions on the length of this name, but long names are likely to be truncated in some wallet applications, so it’s best to keep the name short. Then we have the symbol. In this case, I’m using symbol, UDC. The symbol of the token contract is the symbol by which the token contract should be known, for example, UDC in this case. It is broadly equivalent to a stock symbol and although it has no restriction on its size, but it is usually three to four characters in length. Decimal ones, that’s an interesting one. Now, decimal refers to how divisible a token can be. So, if you see in my case, I’m having my decimals equal to 18. So, let me give you a little bit more detail on what it means. So, like I said, decimals refers to how divisible a token can be from zero, not at all divisible to 18, pretty much continuous. Technically speaking, the decimal’s value is the number of digits that can come after the decimal place when displaying token values on screen. The reason that decimal field exists is that Ethereum does not deal with decimal numbers, it can only deal with integers. Let me explain you this with some examples. For example, if you have a licensed token, a token that represents a software license for a given software product. That means, the users holding a licensed token will have access to the software. It makes no sense for the user to hold a fraction of a license, right? So, the token creator sets decimals to zero. In another case, let’s say we have a gold token where users can hold some amount of gold. Let’s say one token means one kg of gold, but we would like users to be able to buy lesser quantity if they wish to. Since in Ethereum and Solidity, we cannot represent decimals, so we can make our gold token divisible into smaller parts, and hence we can set a decimal value to 18.

20. C4L3 Concept 20 ERC Walkthrough Part 2 V2-UU1ficO0lBc.en

Now, let’s look at the six mandatory functions of an ERC-20 token contract. So, we have six functions right here, totalSupply, balanceOf, transfer, transferForm, approve and allowance and we also have two events that we will also talk about in this video. So, let’s talk about totalSupply, the very first function. Right, there’s ERC function, totalSupply, public constant returns uint. totalSupply equals the sum of all balances, that means, the total amount of tokens available. When you initially create a token contract, you start with providing a total supply, which means that this is the maximum supply of tokens that can circulate between various addresses. When tokens are transferred from one account to another account, the token contract will update the balance of the two accounts. Just some extra details about this function. It is possible to change this total supply by two ways. Either by minting new tokens, which means creating new tokens or it can also burn tokens which means that will decrease the supply of tokens. We can also burn tokens by sending them to an address zero. Now, this will not change the total number of tokens, it will just make those tokens unavailable. The next function we’re going to talk about is a balanceOf function. It takes an an address, public constant returns a balanced. The balanceOf function provide the number of tokens held by a given address. The function accepts an address as a parameter. Now, since you see that this function is public, the balance of any address is viewable by anyone. Remember, we learned about mapping just about a few lectures back. This is what is used by a token contract to implement the balance of addresses. We will see that implementation soon. It just uses a mapping to store balances of all addresses. The next function we have here is a transfer function. Takes any new to address, number of tokens and then returns success, true or false. So, the transfer function lets the owner of the contract sent a given amount of tokens to another address, just like a conventional cryptocurrency transaction. Note, that there are no checks made on the recipient address. So, it is important on the side of the sender to ensure that the recipient is valid, otherwise, you can lose your tokens. It has two input parameters. The first is the address to transfer the tokens and then the second is the number of tokens or the amount of tokens and then return, it returns a true or false status. The next function we have transferFrom function. Little bit complicated. I’m going to explain you really good so listen to this if you really want to recap and listening again. Definitely do that. So, the transferFrom function allows a smart contract to automate the transfer process and send a given amount of tokens on behalf of the owner. Let me explain it. Now, you might ask what is the difference between transfer and transferFrom functions. Let’s consider transferring money to pay a bill. Now, one way is to send money manually, by taking the time to write a check and mailing it yourselves to pay the bill. This is like using transfer. So, you are doing the money transfer process yourself without the help another party. Another way would be that you could set up an automatic bill pay with your bank. This is like using transferFrom function. Your bank sends the money to pay off the bill on your behalf automatically. With this function, a contract can send a certain amount of tokens to another address on your behalf without your intervention. So, you approve another contract to use money on your behalf. Now, if you see, this function transferFrom, it takes three input parameters. The from address, the to address, and the amount of tokens and returns a success of true or false. Now, important thing to understand here is that the approve and the transferFrom, if you look at the approve, we will talk about that in little bit more detail in just a minute. Approve and the transferFrom function are two functions that work using a two-step process. In the first step, a token holder gives another address of a smart contract approval to transfer up to certain amount of tokens known as allowance. Now, the token holder uses approve to approve this information. In the second step, the smart contract who has been approved can take up to the allowed number of tokens from its allowance and use the transferFrom function. Now, all of these functions will get more clearer as you start to implement these functions. Remember, this is just an interface that is asking us to make sure that all these functions are implemented. It is our responsibility to implement them once we have or we need to deploy a contract or a token. Let’s talk about the next function, function approve. When calling this function, the owner of the contract authorizes or approves the given address to withdraw tokens from the owners address. The next is the allowance function. It takes into input parameters, token owner and spender. The allowance function provides the number of tokens allowed to be transferred from a given address by another given address. Note, that anyone can query any addresses allowance as all data on the blockchain is public. Allowance is mostly implemented by a mapping inside a mapping. So, we have a mapping where the keys in address and the value is a mapping of addresses to tokens. We will see this in example very soon. Then the last thing I wanted to talk about is the two events. Now, ERC-20 defines two events that must be triggered when the contract takes relevant actions. The first event is a transfer event which should be emitted when the contract transfers tokens from one address to another address. We will see an example soon. The second event is approval event would should be emitted when one address approves another address for spending a specific amount of tokens. Only then you have this contract standards implemented when you have all these functions defined. So, again, now these are just function declarations. It is your responsibility to write and implement them in your contract. Once you’ve done that, this is when you are going to adhere to ERC-20 standards and your token will be called ERC-20 tokens.

21. C4L3 Concept 21 ERC20 Using Remix V2-_6Wv_D8p9n4.en

Now, there are many ways you can get started creating your own tokens. I’m going to show you a couple of ways, in fact, two different ways. In the first way, we will implement all these functions ourselves and then deploy it to locally running JavaScript VM. Now, I’m in my Remix right now and we have the JavaScript Virtual Machine, which is an in-browser Ethereum Network running in right now. We will use Remix for this whole process, which is my step number one or my process number one. Now, I’m going to do this to show you basic function implementation. So, all the functions that I just showed you in my last video, that you have to implement the mapping and the transfer events, we’re going to write these functions down. But, also at the same time, I will let you know that we’re not going to implement any error handling yet. So, I’m not going to deploy any public network using this process. My second way that I’m going to show you in the next video is, of course, going to be my preferred way. But, for this is something really important because it really help you understand how this whole thing works, okay? So, let’s walk through, so all these functions that we just talked about, if you look in my standards that I showed you. So, this is a basic standard what it looks like. We talked about in the previous video. So, now implement this, now this is a file that I’m implementing, so calling it contract myToken is a name of my token. So, if you see we have three optional things here, so I have the name, symbol, decimals, and I’m going to implement that. So, I’m going to see my name, I’m going to call it Udacity Token, and I’m going give it a symbol of this and this. I’m also setting a initial supply to total supply. What I’m doing is that in my constructor function, whenever I initiated the contract, I’m getting an amount, and I’m setting my total amounts to those many tokens. So, that means when the contract is initiated, it’s going to set the total initial supply, which is _totalSupply as per the input argument, and we’ll talk about that in just a second, and then we have a mapping, that is storing the balances, like I said, “The best way to implement the storing your balances, is using a mapping.” So, this is about mapping for each account, stored using a mapping, address of the account, and the number of tokens at the address has. Now, we will talk about mapping in just a second for the second allowance, but let’s just talk about the constructor function. So, what we’re doing in the constructor function like I said this is called automatically, when the contract is initiated. It sets the total supply as per whatever the input was received, and it also gives the initial supply to the msg.sender. Remember the msg.sender is the one who is initiating the contract, we learned about this in one of our previous videos. So, what it’s doing is that it’s accessing the balances, mapping, with the square bracket notation like we logged in mapping, of the msg.sender, and it’s setting. So, it’s giving all the initial supply of whatever the number of token to the person who is creating the contract. So, that’s happening in the constructor function. Now, the next mapping we’re implementing here is, now remember we talked about forth allowance. That one address can allow another address to spend these many number of tokens from the initial owner’s account. So, what we’re doing is that we are someone from the owner of the account, it proves the allowance for another account, creating an allowance, mapping, right there. So, this is a mapping of an address, and another mapping inside it. So, the first key is the owner of the tokens, this address, and the second mapping it says, “Who can spend on your behalf, and how much?” So, which address can spend how much, forward address. So, we are creating a mapping with the keys and address, and the value is further a mapping of address to amount. So, that’s the two mappings we’re implementing here, and then we have two events we talked about. We are supposed if you look in the standards, we are supposed to implement two events, so all I’m doing is at implementing or writing those two events down. Now, these are the six functions, of course, we have the constructor function, and these are the mandatory functions, totalSupply, balanceOf, transfer, transferFrom, and approved, and, of course, allowance, is this one right there, which will also be a function. So, now let’s talk about the very first function we have the balanceOf. Now, the total supply in fact the first one, the total supply all it does is that returns the total supply of tokens. So, if you call this function, is going to give you the total supply back. Now, this is a supply that we initially set in our constructor function. That’s the first function, the second function we’re implementing is the balance of function. So, it’s getting an address of the token owner. That means and, again, a public function, that means anyone can query and find the balance of an address. So, this function it gets the token balance for an account token owner, and it returns the balance. So, if you see the return values are uint value. So, we’re accessing the balances, mapping for the address given to us with a square bracket notation. This is how you access mappings, and then you’re returning it. So, that’s the second function, and the third function that we are implementing here is a transfer function. Now, again, if you see these are all the functions that are pretty much coming from my standards. Again, I’m going to show you. We are having three optional things. We have two event and six functions. Now, this is anytime you implement these functions, it is mandatory, that’s the only way you can make an ERC-20 standard token. So, the next function, so we talked about totalSupply, the next function is balanceOf, we talked about that, and then we have more functions after that, the next is the transfer function. Now, what this is doing is that it’s transfer them balance from the owner’s account to another account. Of course, it’s going to so once it transfers, you’d have two parameters; input parameters two tokens. So, it sets, so whoever is initiating or calling this function, it’s taking the balance from that msg.sender, and then subtracting the balance. So, I said it decreases the balance from the from account, increases the balance of the to account where it’s going to, and it also emitted transfer event. Okay, and then the returns are true or false, simple. So, if you look at it just one or two times, it’s going to get pretty clear. It’s pretty simple to implement these ERC-20 standards, and the second is a transferFrom function. Now, we talked about this is another way of transferring. So, it’s sending an amount of tokens from the from address, to address, and the number of tokens, and again returns a success. Now, the transferFrom function we talked about in our previous video, is used to allow contracts, to spend tokens on your behalf. So, it spends token on your behalf, and it also decreases the balance from the from account because it’s going away from the from account, and it also, is going to decrease allowance because this had an allowance, right? So, initially when you gave an approval, we’ll talk about approve in just a second. But, it’s also going to decrease, if this account was approved to spend these many tokens, since it’s spending these many tokens, we need to decrease that allowance, right? So, we’re going to decrease that. Now, since remember allowance was a mapping, inside another mapping. So, would accessing good with a double notations allowance, from in msg.sender, and then we have our allowance this and then be decreasing that allowance, and then when transferring tokens, to address. So, whatever the two address that’s we’d need to transfer it, to what transferring the number of tokens, and then we’re emitting the transfer event, and then return true. Then, we have a function approved. Now, this approved the spender to withdraw from your account multiple times up to the token amount. So, the msg.sender is approving this spender to spend these many tokens from the msg.sender’s account. Not also sets up allowance mapping accordingly. This is what is creating the mapping right here, and it also emit the approval event, so we have two events remember, we have the transfer event, the approval event. Since we are approving an account, to spend money from another account. So, we’re sending an approval event which is this way, and return true. So, now this is how you deploy, or you create or implement these standards. Now, I’m going to deploy this to a local JavaScript machine right now. Now, again, just wanted to show you that this is just a basic way of implementing functions, I have not really completely written, but I definitely wanted you to walk through how these all events happen. It’s not implementing the error handling yet. So, it might be rejected as a standardized token, but I’m sure it gave you a nice understanding of these functions, and but I would definitely encourage you to use my next option in the next video, which will go through, but let’s go deploy for now. So, I’m going to go deploy to my local JavaScript machine running right here. So, if you see I’m in a JavaScript environment right now. So, I’m going to take my tokens is given an initial supply of, okay 1,000, we’ll start 1,000, and then we’re going to deploy it. Now, you can also go right there and then look at what’s going on. So, if you see it comes back with a hash that means everything went fine. I’m going to click on this little button right here, so if you see my contract has been deployed this is the address of the contract. So, that’s the address. So, again, we’re in the local JavaScript machine, so we really are not able to go to Ether scan right now. We’ll do that in the next video, but just to local machine, the coined, that token is deployed. Now, let’s go click on totalSupply, income to be 1,000, remember this is what the constructor function did to totalSupply, and also remember, in my constructor function I gave my whole initial balance to the msg.center or the person who created the account, so lets go see if that happened. So, I’m going to copy this address, this is the one that I initiated the contract with, right? I’m going to go paste it in my balanceOf. So, let’s go check the balance of this address, and I’m supposing this should be 1,000, which it is. Fantastic. Now, let’s also try transferring, some tokens from one account to another account. So, I’m going to go in my this environment, I’m going to go, let’s say, so we deployed from this address 147. So, let’s go pick another address, I’m going to go pick the first one, and copy the address, you click on this small button to copy it, and then I’m going to go transfer. I’m going to go back to my this account. Then, if you’ve seen that transfer, I can transfer to. So, I’m going to transfer to my one of the other addresses that’s given to me by the JavaScript VM, I’m going to say, “I want to transfer 10 tokens.” So, let’s click on the transfer event. Now, once that goes through, now let’s go find the balance of this. I’m going to go, again, find the balance, of my address that I just transferred to, and let’s see I’m supposing this balance should be 10. Fantastic, and the balance of the one it transferred from, should now be decreased to 990. Let’s again try that. So, the balance of this one goes to lower. Again, you can always query on the name, we had Udacity Token, we had a symbol, already showed you we had decimals of 18, so all these functions you can always try the transferFrom function. Now, this is just a simple way of understanding how all of these functions work. But, in my next video, we’re actually going to go deploy it to a public test network. We’re going to go use the Rinkeby test network, and that we can actually have physical token really, a digital token and you can also transfer it to your friends that way. So, this was the Remix way. In our next video, we will move on to our Truffle, and then show you how to deploy a token using Infura, to a public test network, Rinkeby.

22. C4L3 Concept 22 ERC20 Using OpenZeppelin Part 1 V3-5bdXpgL93-o.en

I’m going to now show you how to create your own tokens by using OpenZeppelin’s library. It makes a process very easy. What is OpenZeppelin? It is a library for writing smart contracts on Ethereum. With OpenZeppelin, you can quickly build your own token contracts. They have already implement all the functions like we did in our previous video. You just have to define some basic parameters like total supply, name you token, symbol of your token and the number of decimals. So, they’ve implemented all the functions for you. They also implement really good error handling, so there is no need to reinvent the wheel. All you have to do is import one of the token files. So, let me show you this is OpenZeppelin’s GitHub page. You’re just going to go type OpenZeppelin in Google. So, I guess the pretty much the first link opened up as this much is a GitHub page. So, they have bunch of tokens files here. So, let’s go to the contracts one, okay? So, I’m going to zoom in a little. So, you’re going to go to the contracts and then go to token. Then you’ll see you have many different standards here. See that they have 721 typed also, so I’m going to go to the ERC20. Then again, they have multiple different contract. I’m stun. Implement it. So, we’re just going to go pick one. Now, if you see this is what we did in our previous video also, the implemented towards supply. We implemented balance of. They’ve already done this for us, so there is a transfer function. Right here there’s transferring and implemented all the stuff. They have the approved function. They also have implemented the transfer form function. So, they done everything for you. All you need is to give the name of the token, the total supply and some option parameters and you’re all set. So, now let’s go back and use a Truffle to, in fact use a terminal to make sure that we have Truffle installed. Once you have Truffle installed, we’re going to write a simple contract that just imports one of these files. We should be all set to go. Okay. So, let’s go to our terminal now. Okay. So, we have a terminal window open here. The first thing we’re going to do is install Truffle and npm install Truffle. I have that installed already on my computer, I’m not going to hit Enter. So again, the first thing you do is install Truffle. All the commands are listed on the bottom of the screen for you. So, once you’ve installed you Truffle, then next thing you want to do is make a directory for all your folders and all your files and all your contracts and test folders and migration folders, and all those files. So, you’re going to make a file. I’m going to call folder and I’m going to call it solidity. Once you have the folder, you’re going to cd inside the folder again. Okay. Once you have your inside the folder, now you’re going to do Truffle in it, where you will install your initial folders. That Truffle in it installs for you, it installs a bunch of folders, a node modules folder. It’s going to install your initial contract, migrations file and a migrations contract. So, this is where we are going to start working and create more contracts inside it. So, the next thing you want to do like I said is Truffle in it. Once you have everything set up, now we need to install two package, two packages. The first one is the Truffle HDWalletProvider and the second is OpenZeppelin-solidity. The Truffle HDWalletProvider is something that is required because it installs a provider. This is what will connect to your web three to the world of Ethereum. So for doing that you, will do npm install truffle-hdwallet-provider. Okay. So, you’ll do npm install truffle-hdwallet-provider. Again I have that already installed, so that’s one package you need to install and the second whether td installed is npm install the openzeppelin. Now, this is the whole library that comes along with all the input for the contracts that you can import, all the different token contracts. You, we will just import one of them for our existing contract. So openzeppelin-solidity. Again, all the command are listed on the bottom of the screen. So this is what you’ll do, install. Now we have everything all set up., So if I show you we have a folder package, so we have a builds, a build folder, the contracts folder. We are going to make our own contract inside this folder. We’re going to also create a migration file inside this folder. We have these two files. These are the configuration file, the truffle-config.js is used for Windows. The truffle.js is going to use, is going to be used for a Mac. So, we’re all set with our installation of the modules. So, this is, I have a folder already ready here. So, it creates a basic template for you. So, the first step that you’re going to do is, you’re going to go to contracts folder. You’re going to go to contract folder. It gives you the migrations by default. You’re going to create another file here and you can name it. I think I’m going to call it sample token, because that’s the name of my token that I’m calling, some sample token not SOL. Within that I’m going to write this piece of code. Again, this piece of code is again pasted on the bottom of the screen of this video for you. So, what we’re doing is that we’re importing that file. The ERC 20 that we just downloaded and it’s a Node modules. I’ve walked you to that file very soon. So, I’m seeing contract sample token is that contract. So, it’s inheriting from that I’m giving a name of my contract, I’m giving it a symbol, I’m giving it decimals. I’m also setting initial supply already 2,000, since its decim-18 decimals. I’m doing that calculation right here. You can leave the calculation. I just wanted to show you if you want to divide your tokens, so you can do that. Then, you have a constructor function where you are setting. Now these are coming from your ERC 20 contract, because you’re inheriting it. Okay. So, you’re setting these two variables because that’s the contract that’s implementing all these functions. I’m just setting them initially to whatever I want to set to. So, that’s all I need to do.

22. C4L3 Concept 22 ERC20 Using OpenZeppelin Part 2 V3-2gl2Mp73mFc.en

So, in our previous video, we wrote our sample contract, and we’re importing this file or this already OpenZeppelin contract, and then we’re just giving it the basic names, symbol, decimals, initial supply in which deeply deployed. Now, you will see that if you compile it just the way it is we’ve done it so far, it is going to give you an error, since these two functions in the underscore totalSupply, and the underscored balances mapping are declared to be private in ERC20 dot sol file which I’ll show in just a second, by default. So, we’re going to go to this file and make them internal, that means they are accessible from these derived contracts because they’ve just made it private for now. So, I’m going to show you, so you’re going to go to node_modules folder. Once you go to node_modules folder, you’re going to go to your OpenZeppelin, and there’re a lot of the list here. So let’s move on to OpenZeppelin. Then, we’re in OpenZeppelin we’re into a token folder just the way I’ve walked you through the GitHub page exact same base, you’re go into node_modules, OpenZeppelin, token ERC20 in ERC20. But if you didn’t have it, so I’ve already made internal in my case, but these by default are private. So, if you would have just downloaded without, then the npm and without changing it is going to be private. So, this file is not going to be able to access it. So, I’m going to make it internal back. So these two variables here, so the mapping one and the totalSupply one. Make sure they’re internal, not private. Because if it’s private, it’s not going to be able to access this from that function. So, make sure you take care of that, the very first thing that you’re going to have to do. Now, you’ve done with us. Now you’re going to change this two variables to internal. Make sure to save this file for sure, you have to do that. Now I’m also going to show you to deploy this contract with local test network and also then to rinkeby with the public test and file. Because once we create our token, of course, we need to be able to send it to our friend’s. So, we need to be in some public network. Let’s first of all just deployed locally just to show you the process. I’m going to close this file, since we’re done with this file that’s all we needed to change in this file. Also wanted to show you before we got deployed, there’s a couple of things that you wanted to make sure that you take it of it. First is a truffle.js file. We’re going to go to our truffle.js file, and you’re going to type this code in your truffle, again, the code is mentioned in the bottom of the screen. I’ll walk you to the code also, so let’s go to a truffle JS file which is this one. For Windows, you’re going to go to truffle-config.js, I’m on Mac, so I’m going to truffle.js. Now, what I’m doing here is that I’m actually giving it two different environments. So, either you can deployed on migrated to a local network or you can also deploy to a rinkeby network, so we need to give this two options. So, this is my when I run my truffled wallet it runs on nine, five, four, five, and I’ll show in just a second. Then this is for rinkeby. Now, if you see it just comes in fact when you downloaded the truffle and you start open it you will see that this is given to you. So, what is this here? This is the rinkeby. So if you want to deploy to rinkeby, you have to create your own provider, and this is what it is doing. So, creating a provider the very first link here that we have is a link that is coming from MetaMask. So, this is the link for MetaMask. If you have MetaMask installed which you should by now, then you’re going to get this is the initial seed that MetaMask gave you when you downloaded MetaMask. The second is Infura link. Infura again, I think we worked on that video just about a couple videos back, but again if you don’t have Infura I’ll walk you. But just a second this is the link that’s coming from Infura that gives you, or that you’re hosting a node, or using one of their nodes to deploy in the rinkeby network. So, let me show you how you would do that. So, you’re going to go to Infura. I have everything already set up here. But if you don’t, you just going to go to infura.io, and I will have the links for that in the bottom of the screen, and then you’re going to say, click on get started for free I’m already signed in for now, but you’re going to click on get started for free. It’s shows something right here. Then what it does is that once you sign up, it’s going to send you an email, you have to confirm that email address and just then go back on the website, that’s it. Now, what we need to do is get your API key. This is a key that we note. The easiest way to do that is you’ll see a link here that says learn how Infura works, and just skip on it, and then you’re going to see the screen, that’s it. Pretty simple, create an account, confirm your email address, and then get started. There’s a skip button on the side, and that’s it, and then you’re going to see a screen like this that says Create New Project. I’ve already created that and then you’re going to give a name to your project. So, creating a project is going to give an empty project. I already have done that, so I don’t have to do it. Now, from the end point, you are going to copy whatever node that you want to deploy it to, or whatever network you’re want to deploy to. So, I’m going to do rinkeby, and I’m going to copy this. Now, this is what you need that you’re going to connect to. So, I’m going to take this code, and I’m going to paste it back in my, which I already have, in my right there. So, this is my node that I’m using the rinkeby node. So, that’s all. This is the truffle.js file. Make sure you save this file because once we all set with this, this is the whole part that you have do, and then in the next video we’re going to start deploying it.

22. C4L3 Concept 22 ERC20 Using OpenZeppelin Part 3 V3-dYwuv9coVLw.en

So, in our last video, we actually took it off the inferior parts. You got an inferior key. You also make sure that you have human mask seed in everything. So, this is what the file would look like. So, you’re giving it to environments, because we’re going to deploy it to our local network, and then we’re also going to deploy to the rinkeby network. So, once you have setup, there’s another thing that you would like to take care of is you have to create inside the migrations folder. I’ve already done that. You’re going to create. So, by default, this is only further it comes with, the 1_initial_migrations.js. What I normally like to do, I just copy this code, and I create a file, and this is the name of the file that specifically need to have, 2_deploy_contracts.js. I would just paste it, then I’m going to change it to my name. So, in my case, the name of my token is sampleToken. It’s coming from the sampleToken.SOL that we just created, and then you’re exporting it. So, what is happening in this file is that, inside this file, we first get an instance of the contract that we need to deploy. We’re getting an instance using var sample token, and then we write a function that will be called when we call truffle migrate. Now, inside this function, the bytecode for this smart contract is deployed to the Ethereum network. All contracts that need to be deployed need to be added to this file. They only have one contract for now, but if you add more contracts, make sure you add them here. Also wanted to add, you can always ask constructor in initial values. If there’s a constructor, in our case, we didn’t have that, but we’re already setting our initial value to be fixed in this case. But if your constructor had an input argument, it received, we can write it right after the comma right there. We don’t need it, so I just wanted to give you that information. Now, once this is all set up, we’re all setup with the coding part. So, again, to recap, inside the Migrations folder, we created this file, and then we also edited a truffle.js file to add all this information. So, we have two networks available. We can deploy to a local network using truffle develop, and then we’re also going to deploy it to rinkeby. So, we are all setting with the core, set up with the coding part. So, now lets go deploy, the fun part. So, I’m going to do the first, deploy the locally running network. For the locally running network, let’s go open up our terminal back again. Now, we’re all set with the coding part of it, now we’re going to go deploy it. I’m going to show you two ways. In this video, we will deploy it to a locally running network, and we’re going to run it using a truffle develop command. In the next video, we will actually deploy it to the main rinkeby network using an inferior key that we just created in one of our previous videos. So, now get started to deploy it. We’re going to first of all run our local network with the UDL. You do that is using truffle develop. Now, you will see it starts to run in just about maybe another five or ten seconds, and if you see it gave you bunch of accounts. If you see, this is the port number, the port 9545, if you remember the truffle, our config file, the config.js file, we had a port number for a locally running network to be 9545. This is where the port number is coming from, because by default, the truffle runs a local network on this port. It gives you all these ten accounts with the ten private keys and a mnemonic. Now, once we’ve done that, the next thing you want to do is compile your contract. For that, all you would say is compiled. Since we’re inside console, we don’t need to say truffle compile, just compile. That’s it. It’s going to compile a contract for us. Fantastic. So, you’ve compiled it. The next thing you want to do is migrate it to the local network. For that, the command is just simple, migrate. Now, if you’ve already migrated at once, you might want to do reset flag. Since I’ve done that, I’m just going to say hyphen hyphen reset. You don’t have to do that if that’s the first time you’re doing a migrate. Now, what typically migrant does, it just deploys the contract on the locally running network. So, pretty fast. It’s already done it. It also gave us an address back. This is the address of the sample token. It’s one that we just deployed. This is the address. Now, since we are running on just a local network right now, you really can’t do anything or going ether crown to check it, which we will do in the next video when we deploy it to a public network. But in this case, it’s just a local network, it deployed it, and that’s the contract address back. Fantastic. So, in the next video, we are going to deploy our token to a public rinkeby network using inferior key.

22. C4L3 Concept 22 ERC20 Using OpenZeppelin Part 4 V3-xY6ag7a9xuQ.en

Okay. So, now we are all set to deploy our token, our token contract to a public network, Rinkeby. Now, the first thing I’m going to show you, you definitely want to make sure that you have enough ether in your balance. The way you can check that, is using your MetaMask. So, going to click on this ”MetaMask” icon on the side. If you have the right network, so we’re going to start deploying this on Rinkeby. If I click on “Rinkeby”, and you see you have two accounts, and one of them has enough balance and the other one of course zero balance. So, I’m going to make sure that this account is selected. If this account is not selected, and if I select this account, and I start deploying my contract, it’s going to not go through just because I do not have enough balance. You want to make sure that this account is selected. If you don’t have enough balance, you can always go to any of the public faucets. All you can do, you can actually infer the very first one that pulls up right there, is this one. If you don’t see that, that’s fine. Just go, type rinkebyetherfaucet, and you will find quite a bit. So, the first one I’m going to go click on. All you’re going to do, is that it really wants you to post an address of a URL. The way it goes is that, if you go to Google Plus, and you take your MetaMask account, and then you just have opposed. All you do is a public post, and you bring that address of the URL that you posted and paste it right there, and then he can request ether. So, what I’m going to do, is go to my MetaMask. Once I go to my MetaMask, I’m going to go to “My Accounts” and I’m going to copy this. Okay? So, I copied my address and I’m going to go to plus.google.com. Once I go there, I’m going to go paste my account address right there. Once I’ve pasted, it’s going to give me a URL box. I’m going to take this URL now, and then go paste this URL right there. I’m going to say, “Give me these many ethers,” you have some options. So, I’m going to choose this option, and then I’m going to say, “Give me Ether”. So, if you see its funding right now, and it probably just will gives you. There’s some limited options, you can choose three ethers and for eight hours, or three options here. So, it’s going to go through and let’s give it just about another couple of seconds, and then it’s going to go through and give me confirmation back. You’ll see my balance in my MetaMask should also go up with the same time. So, let’s go click on our “MetaMask balance”. So, if you see it went, in fact, just went double. I had 3,000 something, though it’s quite a bit more. Now, these are just play tokens, I mean they don’t really have value. But again, really helps you to test and work around the test networks. Fantastic. So, we’re all set. Now, we have this much balance. So now, we are ready to deploy it to a public network, which I will show you in the next video on Rinkeby.

22. C4L3 Concept 22 ERC20 Using OpenZeppelin Part 5 V2-sdk_OOLdgNI.en

Okay. Fantastic. So now, we have made sure that we have enough Ether in our Rinkeby address by asking it from one of the public faucets, and once we have everything set off, we are absolutely ready to deploy our token or a token contracts to the Rinkeby network. The way you do that is you do truffle, migrate. I’m going to give a reset flag because I’ve deployed it already. You do not have to do it if it’s the first time. Then, network, and then I’m going say Rinkeby. So again, these are two hyphen reset and again hyphen, hyphen, network and then Rinkeby, and hit Enter. Now, this probably takes maybe a little bit less than a minute. So, we’re just going to sit and wait for this to go through, and then soon enough, we will have our address back. This is the address of where the contract is deployed. Okay. We are back now and then we have our contract deployed and if you see, we get an address back. So, this is the token address, the name of the token was sampleToken, that we picked, and then this is the address that we just deployed our contract to. So, I’m going to copy this address and let me show you how we can actually find it on Etherscan. So, let’s go to our Etherscan. So, now let’s go to Etherscan window. I’m in rinkeby.etherscan.io, and I’m just zooming it for you all, and I’m going to paste my token address. The deployed address right there and I’m going to hit Enter. Once I see that, you see I see this contract came with the hash deployed from my address. If you see this is my metamask address, and this is, just came in 53 seconds back in then it’s all there. Okay. So, fantastic. So, now we can actually see, we can actually find our token and our token contract on one of the public Etherscan sites. Now, the way you transfer tokens from one address to another address is you want to first of all make sure that you add it to your own account. So, we’re going go to our metamask, right there, and I’m going to go click on the side, and I’m going to say Add Token. I’m going to hit on Custom token. I’m going to paste the token address that we got back. See? If you see, it automatically picks the symbol that we just chose and if you see the balance is perfect. This is the balance we chose, right? Now, I’m going to say Add Tokens. Fantastic. So, now, this token is added to my account. So, now, I own these tokens. Now, I can send this token to any other address and the way I do that, let’s go, if you don’t have more accounts, you can always create accounts. So, click here. You can create a new account, if you want more accounts. I do have accounts. I’m going to go on account two. I’m going to copy this address. So, what I’m doing is that I’m actually transferring some tokens from one account to another account. So, this is my account. I’m going to say, copy this address. I’m going to go back in my account one, and I’m going to now transfer tokens. The way you do that? You click on your tokens, and then you say you want to send it, and then I am already the one that’s sending it account one and I’m sending it to account two. You can just pick it down from down here too or just paste it, and now I want to say, let’s say, you just want to give 10 tokens away. Okay, and then hit Next. It’s going to confirm the gas fee, so hit on Confirm, and just takes about maybe 20-30 seconds for this to go through, and if you say it says pending for now, and soon enough it’s going to accept it and this is exactly how you see it says confirmed transaction, and so now, this account has 10 tokens because I need a phase. If you see my balance went down by 10 tokens, and if I go click on our account two. Now, the way you would see that in this account, you again, need to add the tokens to that, right? So, go add that token, with again, that token address. In fact, we need that token address back. So, let’s go back to my window and pick the token address. In fact, we can also get it from a terminal window. So, this was the address. Okay. Fantastic. So, now, we have that, we have the token address. Go to account two, and I’m going to add a custom token. This one and see it picks up the symbol again, and if you see this has a balance of 10. Fantastic. So, now this account has 10 tokens and my account one has these many tokens because I sent away some tokens. Fantastic. So, this is a fantastic week, and send tokens to your friends, and, now this is the exact same way that you would also use for any Mainnet or just using Rinkeby but remember Mainnet just uses main Ether, which is main money or real money. So, this is just the way you would transfer from any address to another address. It could be a Rinkeby address, it could be a Coven address or it could be any of the Mainnet addresses too. So, this is a fantastic project that we did to transfer tokens, create your own tokens and also be able to transfer tokens from one address to another address.

24. C4L3-24 Lesson Outro-GPKyPnzbXGc.en

Congratulations! You have now learned Solidity, the most popular language for writing smart contracts. You now have the tools and the knowledge to write your own contracts, deploy them on any of the public networks, or even on a local test network. We learned how to use Remix to interact with your contracts and to call various functions on them. You also learned what tokens are, and how to create your own ERC-20 tokens, and then view them on either scan. You also learned how you could send your own tokens to your friends. You are truly getting closer to being a blockchain expert.

img

Part 05-Module 01-Lesson 03_Smart Contracts and Solidity

02. Smart Contracts-9vVT15oyi5Y.en

Welcome to the lesson on the Ethereum Smart Contracts and Solidity. I’m Alina, and I’ll be your instructor for this lesson and the next. In the last lesson, we learned the basics of a Ethereum. In this lesson, we’ll talk about Ethereum smart contracts, what they are, and how you can get started building your own. You’ll learn the basics of how to write and manually test your smart contract. This will set you up to write complex decentralized applications in the next lesson. This will be a huge step towards understanding smart contract development, and I’m excited to teach it to you. Smart contracts on Etherium are programs that can be run on the Ethereum network. These programs are deployed to the entire network and each call to a smart contract is verified by all participating nodes. This allows for trusted parties to participate in complex financial contracts without any third party supervision. Numerous projects are working on prediction markets that allow anyone to bet on a future event and be paid out if their prediction was correct without any central authority. Other projects are working on loans, where anyone around the world can request or offer funds for a loan entirely from a de-centralized smart contract. The concept of a smart contract is not a new one. In fact, it was first proposed by Nick Szabo in the mid-nineties. Etherium however, is the first blockchain to have implemented a smart contracts platform. In comparison to bitcoin scripts, Ethereum smart contracts are Turing Complete. This simply means that smart contract code is non-deterministic, and can have conditional branching, jumps, and for loops. The versatility for what’s smart contracts can be used for has resulted in vastly different developer ecosystems in comparison to Bitcoin. Ethereum developer ecosystem is rich in Turing and open-source projects. Many projects and entire companies emerged with their core tech being built on Ethereum smart contracts. Some of these projects have made quite a stir in the medium. These Ethereum-based projects have distributed the token that they made Ethereum smart contract to the public in what is called initial coin offerings or ICO. Collectively, these projects raise billions of dollars. These projects range from focusing on games, to provide services, to art, to different types of insurance, to credit, loans, derivatives, and even keeping track of physical property. To date, there’re roughly 1,000 such projects that have made a token on top of Ethereum with the help of a smart contract. One of the more successful and creative use cases for a smart contract has been around gaming. One such extremely successful project is called cryptokitties. Cryptokitties is a game that allows you to buy, own, and breed digital cats. Certain cats are worth more than others based on the rarity of their genes. The price release cats vary from just a few dollars to the most expensive kitty ever sold for $140,000 in the digital art auction. A smart contract has to compile down to op-codes that the Etherium Virtual Machine or EVM can understand. Though there are many programming languages for smart contracts, the most maintained one is called solidity, provided by the Etherium foundation. Solidity is the one that we’ll focus on for this course.

03. Solidity Introduction-tugFSNB18m0.en

In this video, we’ll talk about solidity, the most popular programming language for Smart Contracts. Solidity is statically typed, high order language for writing smart contracts that run on the Ethereum Virtual Machine or EVM. It can support inheritance, libraries, user-defined types, and many other popular features for programming language. Its syntax is most compared to C++ and JavaScript. But bear in mind that it’s new and rapidly evolving language, so it does have a number of limitations you might not be used to. The easiest way to introduce solidity is to go through a “Hello World” example. To get going, we’ll use Remix, an online browser-based IDE for solidity. Once Remix loads, go ahead and close out of any default programs that opens and make a new file. Now, let’s make a HelloWorld Solidity Smart Contract. Go ahead and make a new file and call it HelloWorld.sol. The first thing we have to define when writing the Smart Contract and solidity is which version of solidity we’ll be using. For this example, we’ll use version 0.4.24. Next, we’ll use a contract keyword to declare our contract, and we’ll make a variable of type string called message. We’ll give our message variable a value in the constructor by assigning a string Hello World. We’ll then make a function to retrieve our message called getMessage. It’ll be public so anyone can access it, it’ll be a view function meaning, we won’t modify any state, but just view the status of existing variables and it’ll return a string. This function will simply return the message we initialized in the constructor. To compile, you can simply use the keyboard shortcut Command S, or click on the “Compile” tab on the right and click “Start to compile.” The green banner indicates our contract compiled and so now we can run it. Head over to the “Run” tab and from the “Environment’s” drop-down choose JavaScript VM. Don’t worry about any of the other settings. Go ahead and click on the “Deploy” button after the drop-down with Smart Contract selected. You should see a message in the console window in the middle that it’s successfully deployed. We can extend that view to see more details of the contract deployment. Notice that now we have a section called “Deployed Contracts” with expanding arrow next to it. Click on it to see the deployed Hello World Smart Contract. Here, we can see that the Smart Contract we deployed has one method that we created called getMessage. Go ahead and click on it. In the console, you should see your request to call the method being executed and on the right hand side, you should see the output HelloWorld. Congrats, you’ve now completed your first solidity Smart Contract program. Next, we’ll create some more complex solidity programs using more advanced tooling.

04. C4L2-04 SC Identity Smart Contracts-oT7NTjwSmpY.en

In this video, we’ll talk about what identity means on the Ethereum blockchain. Identity can be defined in many ways. It’s an extremely broad topic that might involve tying your real-world identity to an Ethereum public address. However, for our purposes, we’ll just say that you’re blushing identity is your theory and public address. This means that when a smart contract allocates resources to user, just given that user tokens or other assets, they’re doing so by using that user’s public Ethereum address, which is also called the wallet. Let’s explore the Ethereum blockchain and see if we can deduce some pieces of information from some of the users on the Ethereum blockchain. Let’s go back to the CryptoPunks website and look at one of the owners for one of the Punks. Here we can see that this particular Ethereum public wallet is the owner for this CryptoPunk. We can then use an Ethereum blockchain explorer such that Etherscan to see more information about this user. Here we can see their entire transaction history and see what other assets that wallet has as well as what smart contracts this wallet interacted with. Etherscan is really good at showing you transaction histories, but not so great at viewing what other crypto collectibles as wallet has. Other websites like Rare Bits specialize in figuring out what crypto collectibles a wallet has, and so here we can see that this wallet also has some other crypto assets. To summarize, even though we do not know the real identity of the user for this random wallet, we can say that this user’s blockchain identity is their wallet. In short, Ethereum public address allows you to have an identity on the Ethereum network. It allows for smart contracts and other users to allocate resources or assets to your wallet.

05. C4L2-04-1 SC Building a Star Notary Service-oLV2dLjTtJI.en

Now, let’s make a star notary service which will be a smart contract represent a star that a person could own. Let’s go back to remix that we used before and make a new file. We’ll begin this just like we did before by defining first the solidity version that we’ll be using. Next, we’ll start our contract with a contract keyword and the contract name. Let’s begin by given the star a name. We’ll initialize that variable field for the star name, and then in the constructor, we’ll assign the star name to be any name we want. Great. Now, let’s add logic for the star to also have an owner. To do that, we’ll need to make a new variable field to hold the star owner. Notice how both the star name and the star owner variables are public. This means that anyone can call the smart contract and ask it for those public variable names, then let’s make a function to claim that star. We’ll start our function with the function keyword followed by function name and any type of parameters. Lastly, we’ll say that it’s a public method that’s accessible outside the contract. Great. Now, all we have to do is set the star owner variable to be the color of this method. In solidity, we have global variables to get information about the transaction. So, all we have to do to find out who initiated this function call is to look at the msg.sender variable. I highly encourage you to check out the link to solidity’s documentation about other global variables and what they’re used for. Now that we have our contract, we can manually test it out just like we did before with the HelloWorld example. Let’s first compile and make sure that there are no compiler errors. Now, we’re ready to deploy. Look at the run tab on the right, it’s like JavaScript VM for the environment like we did before, and click on the deploy after selecting StarNotary from the drop-down. Great. It deployed the test environment in our browser. Notice now that we have two of the variable fields available for us to call as well as the function that we need. This is because all these fields knows more contract are public. Let’s look at what the star name is. Great. The output is what we expected it to be. Now, let’s see who the owner is. If you notice, the owner is zero because there is no owner yet. Let’s go ahead and click on the claimStar and check who the owner is now. The owner should be the account that you used to initiate this function call, which you can see on the top. We can change your account to be something else and claim the star with a different account, and now the star has a different owner. Congrats, you just made a smart contract that tracks ownership of a digital item. In the next lesson, I’ll show you how to set up your local test environment to help us add more complex logic to our star notary service.

06. Private And Public Ethereum Blockchains-N-opdvwU46E.en

In this video, we’ll talk about the difference between private and public blockchains. Ethereum is a public blockchain. This means that any computer from around the world can participate in the Ethereum network. We call such computers nodes, and anyone with access to the Ethereum node can create their public Ethereum address that we call a wallet. A private blockchain operates very similarly, except that it doesn’t allow just anyone to participate in this network but only those nodes and users that are permissioned to do so. You may have a private version of the Ethereum blockchain, but then that network cannot be part of the public Ethereum network that we’re all familiar with. Private blockchains have entirely different use cases. For example, JPMorgan, a huge financial institution, is developing a project called Quorum, which is a private version of Ethereum. It’s intended to be used by enterprise companies who need to be very careful about what nodes can handle their sensitive financial information. Private blockchains allow you to control what nodes participate in the network. Because there is a centralized authority that controls the participant list, private blockchains by definition are highly censored. The motivation behind running private blockchains is that you can allow only trusted nodes to participate and operate on sensitive data. In this course, we’ll learn about a popular Ethereum local test environment that’ll just run on your computer. Because this test environment is local and accessible by only your computer, we can technically call it private. To run a local version of Ethereum on your computer, we’ll use a great tool called Ganache. Ganache is a very easy to use and well-maintained tool to help you develop on Ethereum in a local environment. Follow the instructions below on how to download and install both Ganache and Ganahe CLI. If you’re comfortable with command-line interface tools, I’ll recommend using Ganache CLI. But also be aware that there is a graphical user interface version for Ganache as well. If you’ll be using the command line tool, go ahead and open a terminal window and type ganache-cli after installation. You’ll see your local network being initialized with 10 test account and their private keys. All of them are loaded with 100 ether each for you to play around with. If you’re using the graphical user interface, all you have to do is open the app, and you’ll see the same thing in a graphical format.. Okay, let’s go back to Remix. If you’re using the same browser and computer, then Remix will automatically save all your previous work. You should see the simple star notary contract we worked on before. We won’t change any code, but we will change the environment to where our code will be deployed. Last time, we used a test environment in the browser. This time, we’ll deploy it to our Ganache local network. Go back to the run tab, but this time, choose Web3 Provider from the environment drop-down. It’ll ask you if you’re sure you want to select this option, and click “Yes”. Next screen is going to ask you for the end point of the Ethereum node you want to connect to, and it should be prepopulated with a local Ganache network that’s running on your computer. If you use Ganache CLI, this should be localhost:8545, and if you’re using Ganache’s graphical user interface, the endpoint should be localhost:7545. Also note that if you ever stop your Ganache app or process, you’ll have to reload the Remix page and redo the steps to reconnect. Once you specified which network you want to deploy to, go ahead and click “Deploy”. If you look at Ganache, you should see that transaction go through to create your contract. With the command line, it’ll look something like this. If you’re using the Ganache graphical user interface app, it’ll look something like this. We can use Remix just like last time to make calls on your smart contract, and you’ll see that these transactions go through Ganache instead. Congrats, you deployed your first smart contract to local tests Ethereum network. Deploying to one of the official Ethereum test networks or even Ethereum main net is just as easy. To recap, in this segment, we learned how to deploy our smart contract to our private local version of Ethereum. This allows us to have greater visibility in how our smart contract would behave on the real Ethereum main net. On the next lesson, we’ll continue to build onto our smart contract and introduce more complexity to build a full-blown decentralized app.

08. Interact With A Smart Contract From A Webpage-Z-Ur0_-AdmE.en

Now that we have our smart contract ready to store a star in this deployed tar local Ethereum test network, let’s now build a simple web page to interact with it. I’m going to be using Visual Studio Code as my IDE or Integrated Development Environment and I highly recommend, but please feel free to use any editor of your choice. Go ahead and get the support files for this section. You should find just a simple index HTML page, and some very basic CSS to make it look pretty. The first tool that we’ll learn about is web3.js. web3.js is a JavaScript library that has a collection of helper tools and modules that will help us to talk to an Ethereum provider or node. In this case, the Ethereum provider that we’ll use is the local test network that we have deploying our smart contracts to. Okay. Now, let’s look at index.html file that was given to us. Notice that on line seven, we’re importing our style sheet, and on line nine, we’re importing the web3.js library that we just talked about. Now take a look at line 32. Here we are instantiating our web3 object using the Ethereum provider which in this case, is our local tests network that lives on our local host on port 8545. Remember, if you’re using Ganache graphical user interface instead of the command-line tool, your local Ethereum test network will be on port 7545 instead. Now that we have our web3 object, we can use it to talk to our Ethereum test network. For example, here we can grab the top account or wallet associated with our local Ethereum test network, and set it as our default account. By setting it as our default account, they’ll be used whenever we make calls to our smart contract. Take a look at the codes up here. In this section, we’ll grab the application binary interface or ABI of our smart contracts, so that we can build a Javascript representation of it. This gives us the ability to call the functions and variables associated with our smart contracts from within our webpage. We’ll then construct a reference where I already deployed smart contract by specifying the contract address for where it was deployed on the Ethereum network. Next, we’ll write methods to display information we’ll get from smart contract like name and owner and enable functionality to claim a star or a button on our webpage. Let’s go back to remix in order to get the ABI for our smart contract. Within the compile tab on the right, we’ll click on the details button. Here, we’ll see a bunch of details about our smart contract. The section we care about right now is called the ABI. We can look at what the ABI has. For example, here we have claimStar which is the function that we wrote. Here, we have a constructor, and the next two are starName and starOwner which are functions so that we can view the public variables that we wrote. In order to get the ABI, click on this button to the right of it which will copy the value to our clipboard. Let’s go back to the code. Find the place where we need to place an ABI and go ahead and do just that. Great. Now, we have a Javascript representation for our smart contract. Next thing we’re going to have to do, is grab the contract address, and paste it in here. Since we use remix to deploy, we can find the smart contract address and limits as well. If you go to the run tab on the right, we’ll look at this deployed contracts that we have. Here we have StarNotary deployed at this particular address. To get the address, you can click on copy value to clipboard button again and paste it in here. So now, we have an interface for our smart contract, and we know exactly where in the blockchain it is. Now, we can use this in order to get values from our smart contract that is now deployed on our test Ethereum network. So, to get the starNotary name, all you have to do is call the starName function, which as you can see here returns an output of type string. Now, because everything dealing with blockchain is asynchronous, we’re going to get a callback function. The callback function is going to have an error or a result. If we don’t have an error, then we know we have a valve results, and we can put this valve results into the label for our starName. The label here has an ID starName. So, we’ll go ahead and use that. We’ll set it to the results. If there is an error, then let’s go ahead and make a console log so that we can debug further if we do have an error. Great. Now, we can do something very similar for the starOwner as well. We can call starOwner, which once again, gives us a callback function of error and result. If we don’t have an error, then we’re good to go. In here, we have a label with an ID starOwner, then we can then grab and set to the results. If there is an error, it’ll go ahead and print a message for us, so it’ll help us debug further. Okay, we also have a button to claim the star. The button is right here, and this is the method that we’re about to implement. Once again, we can call claimStar, which is a method on our smart contract, and it’ll call that method with a default account associated with the web3 object, and once again we’re going to get callback function with an error and the results, and if there is no error, we can reload the page so that our values get refreshed. Now, this isn’t a perfect solution, and we’ll see why in a moment. The reason for this is because blockchain is asynchronous, and sometimes it takes a little bit for it to sync. Just because we call the claimStar method, it doesn’t guarantee that it fully went through by the time I reload the page. I’ll show you how to get around this problem in the next section but for now just be aware that sometimes this may not work and you might have to reload the page twice. Okay, now that we implemented everything, let’s go see if it works. Again just a static page with some Javascript involved. We don’t need anything extra. We can just load it in our webpage. Great. So, we have the star name which is Awesome Udacity Star and for now we have no owner. So, when I click the Claim Star, it will use the default account which is the top account from the test accounts that was available to me from the Ethereum test network, and that account is going to be [inaudible] , and it’s this account right here. Next up, I’ll show you how to better interact with your smart contract by using something called events.

09. C4L2-07 SC Using Events From A Smart Contract-hplcjBpBsRo.en

Some of you might be wondering, how do I know when a function called to a smart contract has gone through? That is an excellent question. One way to do that will be to emit a log within this smart contract or when a certain action has occurred. Let’s go back to remix and look at the Smart Contracts. Let’s figure out a way if we can be notified somehow when this function is called. One way we can do that is by emitting events, which are basically logs in survey. Let’s define our event, the event is going to be called star point as window log the address of the new owner from start. When someone claims to start here will emit this event. All right. Let’s see if this compiles. It does and let’s go ahead and deploy it again. So now, we deployed a new version of the Smart Contract with a new address and because we now have a new event, we use a different API as well. We go back to the compile tab and click on details, you’ll see that the API has one more field, which is an event for star planes. Go ahead and copy that API. If you go back to your code, you’re going to replace the old API with the new one. Similarly, because we had to create a new contract, since launching this needable, it now has a new contract with a new contract address. Go ahead and click on the coffee value to clipboard button again in order to get the new value for the Smart Contract address. Go ahead and replace it with the old one that we have here. Great. So now, we have access to star claimed event. Let’s go ahead and use it here. Before reloading the page like this, let’s first check if the event was fired and the way we would do that, we would create star planed event, which equals starNotary.starClaimed, and we’re going to watch on it, which is a function that once again gives us an error and the results. It was properly fired without an error, that’s when we can reload the page, otherwise we’re going to go ahead and make a console statements, then I’ll go see get debug further. That’s it. Now, we can go back and have a slightly better version. To see how it take a little bit more time because I wanted to make sure that we had an updated value when you start owning.

10. C4L2-08 HS-A Lesson Recap-fNaNx6iDqjs.en

Congratulations on making it through the lesson. In this lesson, we went over the basics of solidity. We wrote a simple Smart Contract that we deployed in our locally Ethereum test network. We also made a simple web page to interact with it. In the next lesson, we’ll dive into the more complex aspects of writing in decentralized app. We’ll learn about the Ethereum improvement proposals and standards, and use the numerous development tools of the Ethereum development ecosystem has to offer. Let’s get to it.

img

Part 05-Module 01-Lesson 04_Tooling for Smart Contracts

01. Lesson Introduction-r30vJUrGKiQ.en

Hello everyone. Welcome to this lesson on, tooling for smart contracts. In this lesson, we’ll introduce various tools and open-source platforms for faster smart contract development. These tools will help us achieve more complex functionality, and increase security of our smart contracts. We’ll go over how to use a great tool called Metamask, for seamless interaction with your smart contracts from our web page. Next up, I’ll show you how to write JavaScript tests for a smart contract. We’ll then explore how the Ethereum community accepts new standards and improvements, and how to use the Zeppelin framework to increase security of your smart contracts. Afterwards, we’ll focus on easier web development, and introduce a simple way to deploy your smart contract to the official test networks, and finally, to Ethereum itself. These are great tools that are used for production projects in the industry today. They’ll help you greatly to make an awesome final project for this course. Let’s dive in.

02. C4L3 02 SC Getting Started With Metamask (Slower)-UHIkIRuTrH8.en

The first tool we’ll go over is called MetaMask. MetaMask allows the users on your website to do action choosing their own wallets without providing their private keys for us to do actions on their behalf. It also gives users more transparency on what transactions are being made, based on their interactions with the website. Let’s go ahead and add MetaMask support to our Star notary service. MetaMask currently works as a Chrome plugin extension or as part of the Brave browser. We’ll go ahead and use Chrome and install MetaMask as a plugin. Since we’ll keep using our Ganache look with Ethereum network, we’ll set MetaMask. We received praises given to us when we first launched Ganache. Please note, to never use the seed phrase generated by Ganache as your real main net wallet. This is because the seed phrase generation in Ganache is not random, and other users might have access to your main wallet if created this way. Also note, that whenever we start our Ganache network, we have to redeploy our smart contracts and update the new contract addressing our code. I want us to use MetaMask. We’ll only need a few modifications or JavaScript code. We’ll need to learn MetaMask to inject its own Web3.js object. We will also replace logic, setting in default account. Instead, we’ll ask the Web3 object what accounts are available and take the top one, as that’s the one that we use to select MetaMask. If we want MetaMask to work properly is [inaudible] , will have to host your web page on a local server. To do that, we’ll simply use http-server. Type npm install -g hp - server. The navigate to the working directory for the scores, where the index HTML file is and type http-server. The serial web page now on localhost:8080. Let’s see how our user interactions change. As you can see, now the end-user has a lot more flexibility and visibility into how their actions. They’re actually Ethereum blockchain. We can now change accounts to MetaMask and see you that that affects our results as well. Next, we’ll explore another great tool called Truffle, that’ll greatly help us with tests near a smart contract code.

03. C4L3 03 SC Unit Tests In Javascript And Solidity With Truffle (Slower)-zv7ySiaWTk8.en

In this section, we’ll go over best practices on how to test your smart contracts by introducing the Truffle unit test environment. So far, we’ve only been testing our smart contracts manually, which is by far not the best practice. Since smart contracts is generally pretty difficult, we’ll use a great tool called Truffle. Truffle makes it very easy to write unit tests, mostly Solidity and JavaScript for your smart contracts. I’ll show you how to quickly and easily test your code with JavaScript. First, let’s install Truffle from the command line using NPM by running npm install truffle —global. Let’s make a new folder in your project directory for all our smart contract logic. Go ahead and navigate to it and type Truffle in it. But now initialize this directory for Truffle, and if you look at the directory again, you’ll see that now we have three new folders: contracts, tests, and migrations. We’ll now move our code for our smart contracts from Remix into a new file and the contrast directory. If you’re using Visual Studio Code, I highly recommend installing Solidity plug-in, as it is extremely helpful. We’ll also make a new file and test directory and call it StarNotaryTest.js. We’ll first begin writing our tests by giving the definition of our smart contract. Truffle exposes an artifact object for a smart contract that contains information such as the ABI and other info. Truffle uses the Mocha JavaScript testing framework but with more additional helper keywords to help us test for contracts. Remember those 10 test accounts we got from our local test network? We can use them here as well to write our unit tests. We’ll go ahead and set the owner wallet to the first of those accounts. Now, we’ll instantiate our smart contract needed for each clause. Remember, whenever dealing with any interaction in the block chain, it will be asynchronous. So, we’ll be using the async and await keywords and denote that behavior. Let’s begin testing some basic functionality by grouping your tests in the describe clause. We’ll then create a test to just see the name of a restaurant owner using created correctly in the constructor. Great. Now, we’re ready to run our tests in the command line tool. From the smart contract directory, run a Truffle test. You’ll see your smart contract get compiled and run our tests. Great, it looks like our test passed. Let’s keep going. Let’s test that our star can be claimed. Let’s make a test that it checks that it belongs to address zero initially, and then after the owner claims that, the owner becomes the owner of the star. I’m going to quickly check that our assumptions are correct, and the star first belongs to address zero. Now, let’s add the rest of the logic. Let’s see if those tests worked. It looks like they did. Great. Now, let’s test out the star can be claimed again after an owner has claimed that initially. We’ll put that logic, and then before each clause, and focus on testing just the behavior that happens after someone already claimed it. Now, let’s run those tests, and it looks like that should be it. Congrats. You now know an effective way to unit test your smart contracts for faster development later on. Next up, we’ll go over more complex in theorem App Development Standards.

04. Ethereum Improvement Proposals And Standards-zAOKDmPb5rM.en

In this section, we’ll go over how the Ethereum community proposes improvements, and how that affects the smart contract development best practices. The list of Ethereum improvement proposals, or EIPs, can be found on Ethereum’s GitHub repository. Anyone can propose a new EIP. That EIP then goes through a review process by anyone in the Ethereum community. I encourage you to look through some of the open EIPs, and see if you can provide valuable feedback to the review process because you’re all now part of the Ethereum community. Let’s explore the more readable view for all EIPs. An EIP is one of these types. We will focus on exploring ERCs, which are applicational standards and conventions. Here we’ll see a list of all ERC/EIPs and their statuses. Let’s look at some of the accepted ones. One of the most important ERCs is the ERC-20. Ethereum is the largest, tougher, pretty tokens. Ethereum makes it really easy for anyone to create their own token cryptocurrency with a simple smart contract. Unfortunately, before there was a standard of how to write these tokens smart contracts in order for a marketplace, service, or an exchange to add these custom tokens, they would need to know the contract interface for each token. So, the Ethereum community decided to create a standard or an interface, that would dictate higher smart contract for token should be written. This last marketplace, exchanges, or services, to easily interact with it. In short, ERC-20 is an interface that proposes how token smart contracts should be written. ERC-20 tokens are fungible, like money. If I wanted to spend a dollar, it doesn’t matter if I spent this dollar bill or that dollar bill, as the value of all dollar bills is the same. Non-fungible assets are distinguishable assets that are unique, like land, artwork, or collectibles. Just as we have a way to represent wealth with non-fungible assets in the real world, we have a way to do that with Ethereum as well. The standard to represent non-fungible tokens is called ERC-721, and it looks like this. The authors of this proposal wanted to create an interface that represented all possible distinguishable assets on Ethereum, like physical property, virtual collectibles, or even negative assets like debt. This means that in order for us to make a collection, undistinguishable stars for a star notary that is a true non-fungible asset on Ethereum, we must follow this standard. Let’s go ahead and implement the ERC-721 standard, so we can use it for our star notary service.

05. C4L3 04.1.1 SC Part 6.1 Of Coding Series-WG-zg5mLPg8.en

Let’s go back to the ERC-721 standard description and copy the interface definition. Now let’s make a new file in our smart contract’s directory in the contrast folder for the ERC721 interface that we just copied. We won’t bother with the ERC165 requirement, so go ahead and delete any reference to that. Now, let’s make another contract for ERC721 token implementation. We’re also immediately going to make a test file for it in the test directory called ERC721TokenTest.js. I am going to split my screens that we have the interface in one side and our implementation of it on the other side. Now let’s get started with implementing our ERC721 token contracts. Just like before, we’ll need to specify the version of solidity that we’ll be using. We can use the heritance and say that this contract is an ERC721 that we’ve made before. We’ll need to import our ERC721 interface to make this work. Now we can start implementing the interface requirements. These are event types and they are already fully defined. All of these other functions however, we’ll need to implement. Let’s go ahead and copy them over to our implementation contract. We need to convert these interface function definitions into real functions. We can do that by replacing the semicolons at the end of functions with curly braces. For functions with the return type, we’ll return a default value to get our contracts to compile. That way we’ll unblock tree tests. Notice that none of these functions take the logic for how to create new tokens. So that’s up to us. Let’s make a main function that will enable us to make new tokens. For our main function, we’ll take a token ID which is an unsigned integer. All a token is really is reference of ownership. The way we can do that here is to make a mapping, which is essentially a key value store to keep track of what address owns a token ID. We’ll also make a mapping to hold the balance for each owner address. In solidity, the default value for everything is zero. So, to check that no one else owns the token ID for this given passing time int function, we’ll require that the owner for that token is address zero. To assign ownership of a token ID to user, all we have to do is update our token to owner mapping. To update the user’s balance, we have to update the owner to balance mapping. Let’s also implement the balance of method. This method simply gives the balance or the amount of tokens for a given address or wallet. To get this information, we simply use our owner to balance mapping to get the balance given the owners address. Similarly, the owner of method gives the address of the owner of the given token ID, which we can get by using the token to owner mapping. Let’s look over the three methods that we have implemented so far to make sure they look good. Asking balance of address zero doesn’t actually make sense since all default values and solidity are zero. So, let’s require that the address passed in is not that. Now let’s make sure we adhere to the standards so far. We need to make sure that we emit the transfer event whenever we transfer a token. Since by emitting a token, we’re transferring the ownership from the default address zero to the new owner’s address, we should emit the transfer event on mint. Alright, we’re ready to write some tests.

05. C4L3 04.1.2 SC Part 6.2 Of Coding Series-FUYQ69X6h0c.en

Just like before, we’ll grab the definition of the contracts were testing from truffles artifact object. Just like before, we’ll use the contract cured for our tests and passing the ten test accounts for us to use. The first out of the ten test accounts is the default account that will be used when no accounts is passed in to make a call to a smart contract. It’s usually good to avoid using them for tests as it’s passed in to certain calls without you realizing it. We’ll use the subsequent test accounts to define to users and an operator that we’ll use later. Since everything to do with the blockchain is in asynchronous action, we’ll need to initialize our global contract variable for testing in an asynchronous before each function using the keyword “await.” Let us group the test we’ll write to test creating and token in the describe block. We’ll try and create a token of Id1. So, to be organized, let’s make a variable for that. For this group of tests, the first thing we’ll do is mint the token of Id1 to user1. So, we can put that action and beforeEach function. Next, we can test that user1 is indeed the owner of Id1 using the owner of method. Similarly, we can test that the balance of user one also increased by one. Note that the variable we got back from the balanceOf method is a JavaScript representation of IQN-256, and is therefore represented as a big inch JavaScript object. In order for us to compare it to a JavaScript number, we’ll have to call the two number method on it. Lastly, we’ll want to test that the transfer event did indeed get emitted. To do that, we’ll captured the transaction receipt beget when calling the mint function. And then it’s gets stored as logs. So, we can get the transfer event from looking at the first law of the transaction receipt. Let’s compare that the event name matches what we expect, transfer. We are ready to run our tests. Go back to the terminal and navigate to our working directory for smart contracts. Run the command “truffle test” followed by the test file. Let’s see if our test pass. They do. Great. Let’s keep going.

05. C4L3 04.1.3 SC Part 6.3 Of Coding Series-JMZY1cKQhfE.en

Next, we’ll implement the transfer logic. The standard calls for three transfer from functions, also different, but for the same purpose. The safeTransferFrom functions are there to make sure that the token doesn’t get transferred to a smart contract and gets stuck there. For example, remember our Hello World smart contract? We can transfer ownership of a token to it, but then that smart contract wouldn’t know what to do with it, and that token would essentially be lost forever since you cannot reverse that action. For a real production project, you should definitely implement the safeTransferFrom functions. But for now we won’t, and we’ll just implement the one transfer form function instead. Let’s go ahead and implement the transferFrom function. To transfer a token, all we have to do is update our internal mappings. The tokenToOwner mapping will now have a different owner for that token, and we’ll have to decrement the balance mapping for the old owner. Like before, we’ll have to emit the transfer events to log that that particular token changed ownership from old owner to a new one. We also have to make sure that whoever is calling this method has permission to transfer that token so no tokens gets stolen. We’ll do that using a modifier function that will implement on top. We will require that the only way to transfer token for now is if the caller is the owner of the token that we’re trying to transfer. If the call passes that require statement, we’ll continue as denoted by the underscore. Now, we can take our modifier and apply to the transferFrom method, giving it the caller of the function and the token they’re trying to transfer. Great! I think we’re now ready for some tests. Let’s make another describe block to group all the tests we do with transfer logic. In the beforeEach function, we’ll mint a token to user1, and then have user1 transfer that same token to user2. Like before, we’ll use the owner of method to check that the token now has a new owner. Like before, we’ll also test that the transfer bench was emitted for the transfer transaction. This time, we’ll also make sure that we’re logging all the correct fields. Let’s run our test to see if we can keep going. Great! Next step, we’ll implement the approved method. This method allows the owner of a token to give another address approval to transfer it. This is useful, for example, when you are entrusting another user, exchange or a marketplace to do a transfer on your behalf. For this, we’ll need a new mapping to keep track of what address is approved for a particular token. In our approved method, we’ll simply update the mapping we just made to mark address as an approved address for this token. The only caller that is allowed to set an approval for a token is the owner for that token. So, we’ll require that condition to be met, otherwise, the transaction fails. The standard also requires that we emit the approval event to log this action. This allows subscribers to these events know when a new approver for a token is assigned. To implement the getApproved method, all we have to do is return the value of that mapping for a particular tokenID. Let’s go ahead and change the method signature from external, meaning that it has to be called outside of this contract, to public, so we can use it in our hasPermission modifier function we have on top. Now, we can say that if the caller is an approved caller for that token, that caller also has permission to transfer the token. Let’s write some more tests, and just like before, we’ll make a new describe block to test the approval behavior. I’ll make a variable to keep the tokenID will be minting for the describe block. In the beforeEach function, will mint the token for user1 and have user1 give approval to user2 to transfer it at a later time. Now, we should be able to test that user2 is indeed at proved for that token by using the getApproved method. We can also test that since user2 now has permission to transfer token one, it should be able to do that. After the transfer, user2 should indeed be the new order for token one. We can also test the events emitted is the one we expect, which should be the approval event. Let’s see if we’re good in test so far, so we can keep going. Awesome! All our test passed.

05. C4L3 04.1.4 SC Part 6.4 Of Coding Series-z0BonwqbW6s.en

There might be case scenarios where you want to get permission for an operator to transfer all your tokens and the set approval for our method is just for that. This makes it more convenient for an exchange to the trades on your behalf. This is specifically for operators, they can exchange our marketplace and not an individual person or user. To do that, we’ll create a new mapping. This will be a nested mapping that given a user and given an operator will return a true or false for whether or not they’re operator can transfer tokens on that user’s behalf. To implement the setup rule for our method, we simply set the given operator to have the given approval permissions for the caller of this method. We’ll also need to emit the approval for our event given the owner, operator, and permission status. To implement there is approval for our method, we simply return a permission status in our mapping given the owner and the operator. We’ll change this method from being external to public so that once again, we can use it in our modifier function called has permission. Here we’ll check if the caller has approval over all that users tokens and is therefore approved to make the transaction. Great. Now, let’s test this logic also. So, we’ll have another describe block to test the approval for our behavior. Once again, lamented token ID of one to user one and then have that user given operator permission over other tokens and capture that transaction receipt. We’ll then test if the operator is indeed approved for all the user one’s assets. The other tests we might want to add are similar to the ones we’ve done before. So, let me do those on your own. Great, our test passed. Lastly, there may be scenarios where we might want to test a transaction to fail. Let’s make a helper function that will help us expect a throat or failed transaction. We’ll actually assert that the error for that transaction exists. This might be useful for example to test that a random person trying to steal some tokens, this model allowed to do so. Okay. Let’s run our test one last time to make sure everything works. Great job. That was a tough code in a lot of test cases. Writings to my contracts well requires a ton of test intelligence. Even though it might seem like we wrote a lot of tests here, for a production project we would write a lot more to achieve the highest code coverage possible and test a lot more scenarios. Next step, I’ll show you how to transfer our star notary service to be a non-fungible token.

06. C4L3 04.2.1 SC Transforming Star Notary Into A Non-Fungible Token, Part 1 (Slower)-uCJGnVomLDk.en

Now that we have fully implemented ERC-721, let’s transform our star notary service into an ERC-721 token. We’ll start with a blank star notary contract. First, we’ll import the ERC-721 token contract we implemented in the previous lesson. We’ll use inheritance to say that the star notary contract is an ERC-721 token so that it inherent to all those methods and mappings we implemented before. Let’s write a method to create a star given a star name and its ID. The ERC-721 token contract, however, doesn’t have any logic to hold any metadata for a token. Let’s define a struct that’ll hold all additional metadata we need for a star, which is just the name for now. Now, we can create an instance of the star struct to hold the star name. Notice the memory keyword here. The memory keyword denotes that this is a temporary variable held only in-memory and will be released after the function call. Let’s establish a relationship between the star info and its ID by making a mapping that will map the star ID to its additional metadata. We can now save the in-memory struct we made in our mapping so that it’s saved permanently. Remember the mint function we implemented earlier for the ERC-721 token? Since the star notary inherent from the ERC-721 token contract, we can simply call it here by passing the star ID and all that logic of creating a non-fungible token is taken care of. All right. Now that we have a function to create a star, let’s go ahead and create a test to see if we can create a star and get its name. We’ll create a star of a specified token or star ID and see if it’s named got saved in our mapping. Since the mapping is public, we can access it like any other public method. Let’s see if it passes. Great. Now, let’s say if you own a star, you might want to put it up for sale at a specified price. So, let’s go ahead and make a method for that. That require that only one person who could put up the star for sale is the owner of that star. We need a mapping to denote which star are up for sale and for how much. To save the fact that the owner of a specified star wants to put it up for sale at a particular price, all we have to do is make an entry in that mapping. Next, we should allow someone to buy a star that’s up for sale. We can do that by making a buy star function that is payable, meaning, that this function can accept funds. First, we’ll have to check that the star they’re trying to buy is indeed for sale. To do that, we can check if the price for that star is greater than zero. Remember, zero is the default value for objects in Solidity. So, a star that’s not for sale would have a default value of zero in that mapping even if we never explicitly put it in there in the first place. Next, let’s grab that star cost from the mapping and let’s grab the current star owner. We need to require that the funds sent in this transaction call are equal to or greater than the star price and we can see from looking at the message.value. There’s no need to do anything extra for the funds to transfer, the funds are already located to the star notary contract at the start of this transaction. Notice that, the star that is about to be transferred is still associated with some state. For example, it’s still marked as for sale in our star for sale mapping and the ERC-721 token implementation it might have some approver who is approved to transfer it. The new owner of that star might not want that, so we need to clear the state associated with that star before we transfer it by setting its values in those mappings to zero. Okay. Great. We’re now ready to transfer. If we look at our ERC-721 token implementation, we have a transfer from method. However, in order to call that method, the caller must have permission which they might not have yet, but the rest of the logic we can use. So, instead, let’s make a transfer helper method and consolidate this logic in an internal method without requiring permissions. This is safe to do because internal methods can only be called within the contract or contracts that inherit from it like our star notary service.

06. C4L3 04.2.2 SC Transforming Star Notary Into A Non-Fungible Token, Part 2 (Slower)-hO8qkdELE_I.en

It’s best practice to review the developer documentation. Located within this lesson resource is a link relating to the topic called Visibility and Getters. We will discuss the four types based on this documentation. The first type; Public, accessible by all. A public function are part of a contract’s inheritance and can be either called internally via messages. For public state variables, an automatic getter function is generating. The second type; Private, only in this contract. Private functions in state variables are only visible for the contract they are defined in, and not in derived contracts The third type; Internal, only this contract and contracts deriving from it. Those functions in state variables can only be accessed internally. For example, from within the current contract or contracts deriving from it, without using this statement for the contracts contexts. The fourth type; External, cannot be accessed internally, only externally. External functions are part of the contracts interface, which means they can be called from other contracts via transactions. An external function cannot be called internally. For example, the function does not work, but this.function works. External functions are sometimes more efficient when they receive large arrays of data. As you might have noticed, it’s important to understand the types of visibility you are working with regarding contract functions and state variables. Let’s continue with our StarNotary internal transfer helper. As you might have noticed, it’s important to understand the type of visibility you’re working with regarding contract functions and state variables. Let’s continue with our StarNotary internal transfer helper. We can now use our transfer helper method to transfer the star to its buyer. Lastly, we want to make sure that if the buyer overpaid for some reason, they get a refund and the overpaid amount as returned back to them. We can do that by first checking if there is a difference, and then transferring that different over back to the buyer. Wonderful. We’re now ready for some more test. Let’s create variable for user1, user2, and starID, similar to what we did before. Since we now deal with a creator star, we can create one in the beforeEach function. First, let’s test that a user can put up their star for itself for a certain price. Whenever passing it value at an ether to a Smart Contract, it must be done in Wei. Wei is the smallest denomination of Ether. So, 0.01 Ether would look like that. Since that’s too many zeros to count easily, we can use the web3 object to Wei function to get the star cost in Wei. We’ll assert that after putting up a star for cell, we can see it in the mapping associated with that star’s price. Now, let’s test the buying logic, which is a bit more involved, so let’s make sure to describe a block for it to group those test. We’ll test by buying behavior after the star has been put up for cell. So, let’s put that in the beforeEach function. However, in the real world, we would want to have much more thorough tests to test all scenarios. Let’s test that user2 can indeed buy that star and becomes the new owner. Let’s check the scenario when user2 overpaid for that star. Meaning, they sent more ether than necessary, and let’s check that they got refunded the difference. We can capture their balanced right before the transaction. When the transaction is made, we can pass in gas cost as zero. This only works for the test purpose, so that our math becomes easier and we can capture the balance of user2 right after the transaction. We can then assert that the balance after the transaction minus the balanced before the transaction is exactly the star cost. One test we forgot to do is to see if user1 gets paid for the star they successively sold. Let’s make a described block for the selling behavior. Move the one test we have for testing the selling behavior in there, and add the other one. We’ll make a test that make sure that after a user successfully sells their star, they get the star price that they sold it for. Let’s say they put up their star for sell for 0.05 ether, and user 2 buys it. Their balance after this transaction should increase by 0.05 ether. Unfortunately, this test fails because we forgot about that logic, so let’s go ahead and fix this test by putting that logic in. All we have to do is transfer over the star cost to its old owner at the end of the buyStar function. Now all our tests are good. Awesome. Great job.

07. Getting Started With Zeppelin-tGBxe8-6d6A.en

In this section, we’ll go over an amazing framework for writing smart contracts called OpenZeppelin. OpenZeppelin is a library of extremely useful smart contracts that have followed best practices and adhered to all standards with the focus on security. It’s used by numerous projects and teams making it secure and battled-tested collection of libraries. To demonstrate the extreme usefulness of OpenZeppelin’s ecosystem, let’s go ahead and see how we can write our star notary service with the help of OpenZeppelin. First, we have to install OpenZeppelin. So, let’s go back to our smart contract’s directory, and perform the installation steps needed. Utilizing node package manager, lets initiate the npm initialization command. This time, we’ll use y flag, the y flag allows us to automate the yes for any promptings that exist. Next, npm install with save-exact command. The save-exact command allows us to save the exact version number for the package that we’re installing, in this case, OpenZeppelin for solidity. To view the save dependencies after the installation utilizing node package manager it’s always good to investigate package.json, just to double-check that we have the right package. Considering that we had went ahead and utilize the y command, which can save a lot of prompting, I think it’s a good time right now just to go ahead and double-check this. Yep. Look at that. We have the correct version of OpenZeppelin, and we can proceed forward with confidence. Okay, let’s go check out the OpenZeppelin GitHub repository, take some time to review the ReadMe, within the ReadMe there’s lot of useful information ranging from installation, usage, to security. It’s always good to investigate this. Okay, what we’re going to do next, is navigate to the actual contracts directory. Let’s just double-check where we’re at in regards to creating a new token, we need the ERC721 standard, and sure enough, we have the ERC721 solidity file. Okay, we have some commands that we’re interested in like, balanceOf an ownerOf. So, I think the next step here is to go ahead and go back to our node modules, and we’re going to go to our contracts directory, and you’ll notice it’s very similar to GitHub repository. If you’re wondering, is this a clone of repository? The answer is yes. You can see right here we have the ERC721 solidity file, and it matches the GitHub repository. Look here, we have our balanceOf function with ownerOf function, and our approve function. Okay. This is looking really good for us, let’s go ahead and proceed forward. Okay, next we want to navigate to our StarNotary, and take advantage of OpenZeppelin. The very first thing we need to do to do this, is modify our import statement to go ahead and point it to OpenZeppelin. We know that we have OpenZeppelin by investigating our node modules, so what we’re doing here is putting in that path, it’s a similar path as the GitHub, as well as our node modules. So, let’s just input it right here. This is going to allow us to take advantage of the ERC721 interface from OpenZeppelin. Okay. So, let’s go ahead and bring up the OpenZeppelin solidity file into a new window, so that way we can go ahead and compare command, and migrate over those functions that we’re interested in. The very first function is the mint function. All right, so this looks like the mint function, what we want, let’s go ahead and copy it. We’ll just retype it out here, we’re going to go ahead and remove our current mint function and incorporate OpenZeppelin’s mint function. So, when I put in the message.sender variable, as well as a tokenId variable. Okay. Perfect. Next, we want to go ahead and remove token from, add token to, so let’s do that now. We’re removing our transfer helper because it’s no longer needed, and it simplifies our file considering that we’re taking advantage of OpenZeppelin. So, let’s go ahead and incorporate the removeTokenFrom user, go ahead and take advantage of the removeTokenFrom, put in the starOwner and the tokenId. Next, addTokenTo, message.sender, and then we’re going to incorporate the variable of tokenId. Okay, it’s time to test. During the test you can see that OpenZeppelin is actually being included within our test. So, we know the import statement is working, and our tests have passed. Fantastic. As you notice, that’s the power of OpenZeppelin, to incorporate a library of standards that you can incorporate as interfaces to allow inheritance of various functions and objects that you can utilize within your web development practice’s when you’re creating solidity smart contracts.

08. Infura-y9WECdz3moA.en

Our next tool in our tool kit is to utilize Infura. We want to utilize Infura to help assist us with deploying our smart contracts onto various network types with Ethereum. It’s really beneficial because it saves us a lot of time. Previously, you would have to download the node and synchronize with the network, which we all know is invasive both on our Internet usage for bandwidth, as well as storage with our local systems. So, let’s take advantage of Infura, create an account. After we have our account created, let’s now go ahead and go back to our command line prompt and start the note G command line interface. Let’s pay attention to our mnemonic words. These are like our wallet words that we can use to incorporate within truffle.js configuration. What we want to do is obtain Testnet tokens. So, we went to the Testnet faucet, and we’re going to go ahead and get our wallet address from Ganache, copy it and paste it into a social network feed. So, we can go ahead and fulfill the obligation to request tokens from our Testnet faucet. So, right here, I simply just went ahead and pasted that posting directly into the Rinkeby faucet, and we have a couple options. We’ll select the three ethers initially, so that way we can do another request in a shorter time period. It’s going to take a little bit for this to go through, but you’ll notice that once when it’s complete, you’ll secure the tokens within your wallet, and it will be funded. Once funded, we can continue forward. It’s always good to go ahead and take that transaction ID and verify it with the Block Explorer, so that way, you know in confidence that this wallet has been funded, and you could proceed forward with configuring Infura. After you log into Infura, go ahead and set up a new project. Select the ‘Add New Project’ option, and give your project a name. Once you knew you have your project configured, you have options for the type of network. Right here we selected the Rinkeby network. Copy that to the clipboard. This is going to be the Euro path through Infura’s systems. You’re going to want to paste that in as a provider within your truffle configuration file. So here we have Rinkeby with the Truffle configuration file pointed to Infura. Okay. Next, we want to go ahead and deploy with truffles. So, we’re going to implement the command, truffle deploy, network Rinkeby. What this doing is telling truffle, we want to use the configuration that we configured within our truffle config file to deploy our smart contracts to the Rinkeby test network. As you see here, we’re compiling our smart contracts. The contracts are coming through, we’re not running into any errors. It’s a little slower. That’s because it’s communicating with Infura system versus our local host. So, it’s always best practice to go ahead and establish testing of your smart contracts locally first, it reduces latency. Then, next go ahead and once when you’re ready to test it on the test network, publish it. Right here we have our smart contract within the Block Explorer, and we just got done validating it by copying and pasting the contract address that was reported in our command line interface directly on Etherscan Block Explorer, and just make sure to note that the Block Explorer is on the test network that you selected. Fantastic, good job. With that, you finally took your smart contract, converted it over to be compatible with the Infura network, taking advantage of Rinkeby’s Testnet. Excellent work.

09. Lesson Recap-XrcZrtI2Vfg.en

Congratulations! That was a lot, and you all went through it. To recap, we went over how to use MetaMask in our webpage. We tested our smart contract as we wrote it, to make sure it behaves exactly like we expect to. Afterwards, we explored some of the standards that the Ethereum community established on how to write certain smart contracts, and implemented the ERC-721 standard. I then showed you how to use Zeppelin to leverage the already implemented set of libraries and standards to make smart contract development super fast. Lastly, we went over using Truffle for easier web development and Infura for easy deployment. You’re now fully equipped with some of the best tool in the industry has to offer at this time. You’ll have a blast exploring all these tools to build your uncensored, de-centralized, unstoppable app. Have fun.

Part 05-Module 02-Lesson 01_Decentralized Star Notary Project

07. Solidity-Review 1-3jHs_M-zSA0.en

Hi, in this video we’re going to provide a brief solidity review. As always, for full resources in regards to developer documentation, head over to solidities developer documentation support, utilizing your handling blow. Topics covered in this section are: solidity versioning, contracts, variable types such as booleans, integers, addresses, strings. We’ll go in more detail in regards to variable definition regarding arithmetic operations, we’ll navigate to structs and conclude with mappings. Let’s go over some comments solidity syntax. Now, remember this is geared for quick review. So, we’re going to walk you through some basic concepts, but you should always go ahead and head over to the developer documentation for full review regarding the resources, and tooling for your smart contract development. First up, solidity versioning. Solidity source files can contain any number of contract definitions. Each solidity files also includes a thing called version pragma. It is used to prevent the code from being compiled with future compile or versions that might introduce incompatible changes with your smart contract. Most of the time the definition looks like this. In the example, 0.420 is the desired compiler version. Contracts in solidity are similar to classes in object-oriented languages. They contain data, and variables, and functions that can modify these variables. They’re defined by using a contract keyword, followed by the contract name, and two curly brackets which later encloses the contract variables and its functions. Let’s start by finding out what type of variables there are. First up, state variables. State variables are used to store information on the blockchain. They can also be manipulated by the functions within the contract. Solidity is a statically typed programming language, meaning that each variable must have its type specified. Examples of the main datatypes. Booleans. Contracts only have one of the following values: true or false. The keyword for boolean is bool. Integers can be split into two main groups, regular integers and unsigned integers. Regular integers can store both positive and negative values while unsigned integers can only store values that are zero or higher. Regular answers has keyword INTA to INT 256. The number specifies that the maximum number of bits it can store, thus limiting the maximum value and it could be any number between eight and 256, as long as it’s incremented in steps of eight. The INT keyword alone would be understood as INT 256. Now that you’ve learned to define the variables for your contract, it’s time to go through some basic math commands that will be useful later for defining your smart contracts code, arithmetic operations. Integers can be used for arithmetic operations, such as addition, subtraction, multiplication, division, remainder, exponents and so forth. A real-world example of utilizing arithmetics is referencing back to our pizza example. Here, we define the pizzaSlices, the number of people and the slicesPerPerson. That’s the moment where we need to apply arithmetics. SlicesPerPerson, pizzaSlices divided by people. Next up, structs. As we’ve learned the basics for defining variables, now we learn to create the structure that defines your variable properties. A struck is a special data type that allows a programmer to group a list of variables. Structures are defined like this. In this example, we’re going to define a structure called Car. With that we have some variables like make, model, year, and horsepower. Pretty simple. With that, you can combine structs and utilize mappings. Now, that you’ve defined your variables, we’ll learn how to create a variable that will later map your variable to the blockchain, a special list where all other variables are stored. Mappings allow the programmer to create key-value pairs and store them as a list. Concepts like this are also known as hash tables. Mappings are defined like this. We have a key_type, and the key_value, and then we define it in name. Key_types should be replaced by a data type. Two commonly used variable type for mapping keys, we already know about our addresses and uint. It’s important to know that not every data type can be used as a key. For instance, structs and other mapping cannot be used as keys. Similarly, key_value should only be replaced by the value type. Unlike with keys, solidity does not limit the data types for value. It can be anything including structs and other mappings. Here, we have mapping with the address, assign it at uint256 with the name of balance. This mapping could hold the bank account balance in uint256 for the given address. A quick recap. We went over the definitions of defining your preferred solidity compiler and its version. We discussed variable types, arithmetic, and supporting operations for structs and mappings. I hope that this introduction to solidity helps jump-start your creative process while you work through your project.

img

Part 05-Module 03-Lesson 01_Term 1 Recap

img

assets

css

fonts

img

js

img