Blockchain Fundamentals

  1. Introduction Introduction to Blockchain Fundamentals Blockchain Fundamentals. Welcome to this course on the blockchain fundamentals. This course is the result of many, many months of research and testing, based on more than 20 years of development experience. I am truly happy to present this to you. Learning blockchain development from scratch can be a very frustrating and time-consuming thing to do by yourself. So let's start by looking at the main learning goals. In this course, we are focusing on getting you productive as soon as possible. I will give you everything you need in order to understand enough of the basics and the underlying technology to get you started quickly. There are many implementation of the blockchain technology, but Ethereum is one of the easiest to get started with and it also has a very broad community support and adoption. So that will be the basis for our course. We will delve into how to do contract development on the blockchain and you will be learning about smart contracts. At the end of this course you will be able to do a full end-to-end application development on blockchain. To give you a short overview of this course, here's the modules that we're going through. First it's this introduction and overview. Secondly we will spend some time on the blockchain concepts. The main focus for this course will be on development in Ethereum. To make sure that you're effective right away, I'm going to show you how to set up everything you need on your development environment so that you don't have to struggle to get everything set up correctly by yourself. Just follow what I do in module 4 and you will be fine. The real fun begins with smart contract development. Before we go into making a full application that we roll out to a private blockchain I also recommend that you take a look at the summary and way forward module. It contains some important aspects to take with you. Well, let's not dwell anymore and get right into the next module where you will start your journey into the fantastic world of blockchain development.

  2. Blockchain Concepts What Is Blockchain? Blockchain Concepts. In this module we are going to look at the concepts of blockchain. First of all, what is blockchain? Well, at its simplest core it's really no more than a distributed database. Think of it as a large worldwide computer where everyone can securely access data and execute transactional code. All transactions are stored in blocks of data. These blocks are made in a way that makes them very hard to manipulate or fake once they are stored to the blockchain. Due to the nature of blockchain, you can say that you it gives you a trustworthy way to store data in scenarios where there are no trust. This could be monetary transactions between anonymous strangers on the internet or the ability to securely store your medical information in a way that can only be accessed by those you allow. It is also worth mentioning that blockchain is generally not a place to store large amounts of data for each transaction. You would, for example, generally not store images on blockchain, but you might store information to validate if an image is being tampered with or not. Most data stored on the blockchain is focused on transactions and states of objects, rather than the actual objects themselves.

  3. Bitcoin and Blockchain Before we start to dig into the details, we must spend some time on the origin of the technology. You might already have heard about the emerging currency called Bitcoins. Even though this course does not focus on Bitcoin itself, it is necessary that you have some idea about it. Bitcoin is the first broadly used crypto currency. A crypto currency is something that only exists as a digital currency. It does not hold any underlying value. A Bitcoin is not something you can withdraw from the bank and hold in your hand. A Bitcoin is only a unique string of letters and numbers attached to an ulnar. After the gold standard was eliminated in the U.S. in 1971, this is actually true for the U.S. Dollar as well. You have a balance at your bank account and you trust them to make sure that they keep a secure ledger over incoming and outgoing values. Banks are part of a large global network where transactions can be done between banks and currency can be exchanged. With Bitcoins there is no central system. There is no bank and there is no way to revert transactions once they are done. All transactions are transparent and can be fully anonymous. The underlying technology that enables this is called blockchain and this is what we will focus on in this course. Bitcoins could not have existed without the blockchain and Bitcoins is really its first broad use. Also, let me just briefly give you an overview of the history of blockchain. The notion of a cryptographically secured chain of blocks was described by Stuart Haber and Scott Stornetta already in 1991. The first recognized work on the decentralized digital currency on using similar technology was done by Nick Szabo in 1998. But it took almost 10 years until the blockchain concept was getting mature and published by Satoshi Nakamoto in 2008. Satoshi is by most considered to be the founder of Bitcoin in 2009. However, it is worth mentioning that as of now, no one really knows who Satoshi Nakamoto really is. It is highly likely that Satoshi is not a real person and that it is a pseudonym used by someone else. There are many interesting theories around who it really is and this adds to the mystic and enchantment of Bitcoin and the underlying technology. Race forward to 2014 and the blockchain is hitting a mainstream term used by financial and technical media. Most companies out there in 2014 are still struggling with understanding the usage and impact on their solutions. At the recording time now in 2017, large companies are picking up speed on blockchain development. There's massive investment being done by traditional legacy software companies like IBM and Microsoft, but there is also a large and rapidly growing mass of startup companies getting their blockchain implementations out to the market. Let's look at the characteristics of blockchain. First of all, it is a global singleton. If you know how singletons work for a program, you can think of the blockchain objects as global singleton instances. The blockchain is natively object-oriented where code and data reside together. However, objects are securely separated from each other. It's unstoppable. There is no one in control over a blockchain. It cannot be stopped and it cannot have a central failure. No government or corporation can censor it and it's very resistant to being hacked. There is no power cord to pull nor a single point of attach. Blockchain by its nature is accessible. Everywhere there's internet, you can access the blockchain by using a broad number of clients and technologies. And most of all, it's verifiable. Everyone that has access to the blockchain can verify every single transaction from the beginning of time. This enables everyone to audit everything and as we will learn in the next couple of slides, it is actually quite easy to do so.

  4. How Does It Work? So how does it actually all work? It begins with someone doing a single or a group of transactions. A transaction is typically sending data in the form of a contract. Depending on the blockchain implementation you are using, it can also involve crypto currency being sent from one account to another. The transactions are sent to a large peer to peer network of computers. These are generally distributed all over the world. Each computer is called a node and they all have a copy of the existing data. Then the transaction is executed and validated based on pre-shared contracts and scripts. This ensures that all nodes execute using the same set of rules. When the transaction has executed, the result is added to the blockchain. Since this is done at each node, you would have to compromise every node in the chain in order to compromise the transaction. When doing transactions in the blockchain, there are some aspects that is absolutely necessary for it to have the characteristics previously mentioned. First, all transactions are atomic. This means that the full operation run or nothing at all. Let's say you have a monetary transaction. You would want to ensure that both the function that credits one account and a function that debits another are executed successfully. If one of them fails, the entire transaction should fail. If not, you might end up either destroying or creating money. However, unfortunately, even with blockchain, there's nothing that prevents you from writing bad code so you still need to ensure that you execute transactions in the right order. Secondly, transactions run independently of each other. So no two operations can interact or interfere with each other. It has to be inspectable. Every single method call that comes to blockchain comes with the actual address to the caller. Just think about it. This gives a unique possibility for securing and auditing solutions on a very, very wide scale. This is unique to blockchain. At least I'm not aware of anywhere else you can do this. Blockchain objects are immortal. That means that all data from an object are permanent. The code for an object can never be changed and you can never delete an object externally. The only way to remove an object from the blockchain is that if it is programmed to remove itself. So think about it. When writing code for the blockchain, you really, really, really need to make sure that this is what you want to do. Because you never alter or remove it.

  5. Hashing The core of any blockchain resides in the concept of hashing. Hashing is basically to execute a mathematical algorithm that creates a result with a given length regardless of the input given. The result of a hashing function is called a hash and you can think of them as digital fingerprints. Hashing is a one-way function, meaning the function will always return the same result given the same input, but you can never regenerate the input based on the result of the hashing algorithm. As a simple example. Let's say that we have a very simple hashing algorithm that takes any number between 0 and 45 as input. The algorithm then doubles the number and rounds to the nearest 10. This means that if input 5, you will get a hashing result of 10. The same will be true if you input 3 or 4, but if you input 9, the hash will 20 instead. The length of the result will always be two digits, even if you give a single digit input. If you run the algorithm several times using the same input, you'll always get the same result, but you would not be able to figure out what the input was. When hashing in real life, a much more advanced hashing algorithm is of course used. The most used hashing algorithms are generally well known and available to the public. Hashing algorithms are generally created to execute fast. The more advanced you want your algorithms to be, the more power it takes to execute. A very common hashing algorithm used with blockchain is the SHA 256. It is one of several checksum hashing algorithms and it will produce a long text string as a result. It's designed by the American National Security Agency and it's made available to the public. The SHA is a family of hashing algorithms. The number following the names lets you know the complexity of the implementation. Let me show you an example with a text from Wikipedia. When we run the text through the SHA 256 algorithm we get the long string you can see here as the result. A very common use for hashing is when storing passwords in a database. If you store the password in clear text in your database, your usage might be at risk if your database is hacked and the hacker gets access to the database table with usernames and passwords; however, if the password is hashed, the hacker will have a very hard time figuring out the passwords. They will then need to compare the passwords with known hashed results where the input is known less well. This can be done by generating a large number of hashes based on random text strings or even by preexisting lists of common hashes. The longer a password is, the less likely it is that the hacker can find the input that created a certain hash and still, if they were able to figure it out, they wouldn't be 100% sure so they would have to test every combination that led to the same hash. Because hash algorithms always give the same result given the same input and always give a fixed length of the result, they are also ideal to verify the consistency of larger amounts of data. If you put the entire Wikipedia website through a hashing algorithm and save the resulting hash, you could easily figure out if someone has changed anything in the website. Even a single comma would result in a different hash result. So when comparing two hashes it is very quick to determine if they match or not. If they match, nothing has changed. If they do not match, someone has made some kind of alteration to the original. This is a very sure and quick way to figure out if the data has been compromised. And another benefit is that you do not need to store the original data to see if anything has changed. All you need to store is the initial hash. Hashing algorithms are also used in countless areas of modern security where the need for consistency is high. For example, in secure communication where timestamps are exchanged. While we are discussing hashing, let's quickly look at a related topic called a Merkle tree. A Merkle tree is a hash of hashes, which makes it quick and rather easy to confirm large amounts of data and transactions. Let's say we have four sets of data. To simplify, I'm using one word here for each dataset, but this could easily be for example, transactions in real life. These words produce four different hashes. In the Merkle tree, groups of these hashes are hashed together to create hash of hashes. These hashes are then hashed together as well, creating what we call a root hash. In order to figure out if something has changed anywhere in the Merkle tree, we only need to see if the root hash has changed and you can then follow the tree down to see where the change is done.

  6. The Block Now that we have some basic terminology covered, let's begin to look at the actual block in the blockchain. A block consists of data and its resulting hash. If we go ahead and change any data in the block, the hash will change and the block will be invalid. It also includes the nounce which is input to the hashing algorithm that would result in the first part of the hash to be something predefined like a set of zeros. It's not possible to predict the nounce so it can be considered as proof of work by the machine creating the hash. Let's say that we require our hash to have a leading number of four zeros. Whenever we change anything, we will need to rerun the hashing algorithm until we figure out which nouns to set. This is called mining the block. Let's see what happens when we have a chain of blocks. When we are looking at the chain, the block also contains a block number, meaning which order it has in the blockchain. A block also must contain a timestamp, but most importantly, the block in a blockchain will include the hash of the previous block. This means that if you alter any of the value in one of the blocks, you will break all the blocks following in the chain. This is also where the Merkle tree I mentioned earlier is used. The only way to fix the blockchain will then be to mine all the blocks after the changed block and make the nounced hashes all over. In blockchain we distribute a chain of blocks to a vast number of computers. This means that the chain exists in multiple locations. Depending on the implementation of blockchain you are using, it could be millions of replications of the chain. This means that we could easily figure out if something has changed, even if one of the chains has been re-mined. The resulting hashes would be different from one chain and blockchain works in a way where the chain that has the most work put into it wins, so to say. The altered chain would then be rejected by the distributed blockchain and be removed. To better understand why it's so hard to fake anything in a blockchain, let's talk a little bit about the concept of forks. First we have our user, Kent. He has a balance of 100 Bitcoins and he wants to buy a new Tesla car. He got the Bitcoins from his very rich, but still down-to-earth mother called Sharon. He finds a vendor that is selling cars using Bitcoins. He adds the transaction to the blockchain and drives away smiling in his electric wonder machine, but when he comes back, he sees a Mercedes that he likes on the internet. The vendor also accepts Bitcoins. Unfortunately, he is now broke, but he kept information about his previously owned Bitcoins. He therefore tries to add a block to the blockchain where he spends the same money once more. This creates a fork in the blockchain and in order for him to fix it, he must have a lot of computing power at his hands. Actually, since the blockchain consists of having to prove that you put work into the calculations, he would have to have almost the same computing resources as the rest of the blockchain in order for his new chain to be accepted. This is quite unlikely, but we have see some people trying to do this, but this fork has always been downloaded and removed. Since it requires so much computing power to do this, it's actually a good incentive to stay honest. The same computing power could have been used to mine blocks legally instead.

  7. Securing Your Data Data stored in the blockchain is generally available to everyone that has access to the chain. This gives some challenges, but it will also lead you to think about security first. In some applications, it's no problem that everyone has access to everything, but in most cases, you want to assure that you control who has your data. There are basically two ways to handle this. The first is obfuscation. This means to make the data relevant only to those who know its meaning. One example of this is with Bitcoins. With the address of any account, it's a long string of letters and numbers. No one in the chain knows who the address is physically connected to and they don't need to know, but everyone knows every transaction going between the different account addresses. It's up to you if you want to be anonymous or not. As long as you don't share a connection to your account address, there's no way for anyone to know that you are the owner of the account. Another example of obfuscation is to have the data contain IDs and status codes. Unless you know what the different IDs are connected to, the data is really of no use to you. The problem with relying only on obfuscation is that you always run the risk of someone making the connections due to a breach in the system controlling the keys and connect the data. To deal with this, you can make use of encryption. When you encrypt a message or the transaction payload, you apply a two-way algorithm to the message in a way that can only be decoded if you know a password or a passphrase. This means that the data can be available to everyone, but only those who have the keys to decrypt the message can make sense of it. There are many different encryption algorithms and as with hashing, they are continuously evolving. I'd like to show you a simple example with what is considered to be one of the most secure in use now called Advanced Encryption Standard or AES for short. It uses long keys to produce heavy-duty encryption. The harder it is to crack. We take our original message and pass it through an AES 128 encryption with a generated key. As you see, we kept the structure of the block, but the message itself is encrypted. The block can still be evaluated and verified by the participants of the blockchain, but the content will only be available to those with the key. If you want to play around with encryption, there are many online tools for this, and if you like, you can copy the message from these slides and run it through an AES decryption with the same key and you should be able to get back the original message.

  8. Public vs. Private Now that we have looked into blockchain as a general term, let's start to consider the implementations of it. First of all, blockchains can be either public or private. In a public blockchain, everyone with an internet connection can connect to the chain. The way the public chains are funded is that you generally need to pay for storage, transaction, and execution costs to the entities that have joined the chain. This can be quite expensive. Just imagine the Bitcoin going from only being worth a couple of cents to over $1000 only a few years later. You might regret paying 1% of a Bitcoin for your transactions back in 2013; however, as soon as the different currencies that are being used stabilizes, this will be less of a problem. Since the public blockchains are generally widely distributed, there's also no given point for attack for a hacker. They cannot target a single datacenter or company to bring down the chain. But this really depends on how well the chain is supported by the community. As soon as the community support is gone, the chain is also gone. This raises a lot of questions and concerns that we really don't have any good answers to yet, but I'm sure that over the next couple years we'll get more research and better understanding of how these communities actually work. One of the biggest benefits and actually a challenge of a public blockchain in a business context is that it is democratic. The community has to decide how for example, forks are being handled and generally your stake in the chain controls how many volts you have. When looking at private blockchain, many consider these to not be real blockchains as they are not truly distributed and democratic. I'll not spend time on that discussion in this course, but you are free to participate in the countless online discussions around this topic. With a private blockchain you are closer to a traditional database. Some people call private blockchains for shared distributed databases. Since you will be owning the infrastructure, you can also control the cost and financing of the chain. This might be both a benefit and a challenge depending on the company goals you have. You're also dealing with known entities and you are in control of who can access your chain. For a lot of companies dealing with sensitive data, it's required by law in many countries that the data is stored in a specific area. For example, in Norway where I live, we're only allowed to store certain transactional data in local storage locations. Since we have much more control with a private blockchain, it can be a very good way for companies to transition to the technology, while legislation and usage patterns evolve. You are, however, losing out on a few important areas and there are also fewer points of attack so your private blockchain might be easier to take down than a public and highly distributed implementation.

  9. The Major Offerings There are many emerging blockchain implementations, but if you look at the current major ones, we have of course the Bitcoin blockchain as the biggest one. Ethereum from Consensus and Microsoft is getting quite a bit of traction from the makers of non-financial applications. It is also the implementation that we will be using later in this course. IMB blockchain on Bluemix is also an alternative for those who want to create their own blockchain.

  10. Usages for Blockchain Now that you know the most important technical aspects of blockchain, let's discuss some of the current usages for it and why it can be such a real game changer. As mentioned many times in this course, the current most broad use of the blockchain is with digital currencies like Bitcoin. Because of the fact that anonymous transactions can be trusted just as much as they can with any bank, this opens up a wide range of new ways to deal with global transactions. Let me give you a real-life example. A good friend of mine is a refugee from one of the most horrific wars in modern history. He managed to escape, but his wife is still left in the country. Making sure that she has the financial means to survive is crucial. Before blockchain, the only option to provide her with money from the other side of the world was by using a money- transferring agency. These are very costly and they take a rather large cut of my friend's limited funds when transferring. Furthermore, the transactions can take many days to complete. And lastly, they require that she shows up personally to collect the money, which is not very safe. With blockchain, however, there is no need for a large transferring agency and there are apps where you can transfer money almost instantly with transfer costs that are only a small fraction. Believe it or not, but even in war-torn countries, you will be able to find internet and transfer the money directly to a mobile device. We are only seeing the very beginning of how these kinds of solutions will change the world in ways we cannot even grasp yet. A small revolution that has been going on for some times is called the internet of things. This is where small smart devices use the internet without human intervention. Right now there are many more devices using the internet than humans. With using blockchain these devices can suddenly do trustworthy transactions securely. An example of this is that your washing machine could order detergent for you when it notices that it's getting empty. Product lifecycle is another where you store all the information on workflow or product in the blockchain. It could for example follow the lifespan of a car from the factory through the seller to the customer into the workshop and lastly, to the recycling plant. Or as we will be doing later in this course, following food to ensure food safety. Certifications are also a great area of use. Certification bodies could issue certifications to products or organizations in a tamper-free and fully transparent way. Secure sharing of data is another example. Given the nature of blockchain, you could insert encrypted information into it and make sure that only those you allow can access your information. This could be used for example with medical information or medical devices in a secure manner. Suddenly, all hospitals in the world could have instant access to your medical folder when needed and you would be able to track everyone that has tried to access your information. There are now devices that will measure the sound of your veins when blood rushes through them. This sound is unique for everyone and it does not change during your lifespan. Just imagine using these sounds are your private key to the data on the blockchain. The making and selling of virtual and digital products has been growing rapidly for a long time now. With blockchain you can market, sell, and even control your digital products like books, courses like these, and music to mention a few. A musician can upload her music to a blockchain and try different models of buying the product. She could, for example, have one price for listening, one for making a ringtone, and another one with a commercial license for using it in an app. All can be done without a major organization taking threat of the royalties. Just try to imagine all the possibilities that lay in front of us now. I'm certain that a lot of you listening to this course will be able to come up with usages for blockchain that no one has ever dreamt of in their wildest dreams.

  11. Summary In this module we have looked at the basics of blockchain and what it really is. Hopefully I've been able to demystify it a bit for you so that you can look past the hype. We had a discussion around hashing and why it's important for understanding how a blockchain works. After that, we started to understand how a block is built and how it is connected to a chain. Security is an especially important aspect to consider so I explained the basics of obfuscation and encryption. At the end we looked at the difference between public and private blockchain implementations, usages, and the current major offerings. Now you are ready for the next module where we will dig into the details of a very popular implementation called Ethereum.

  12. Introduction to Ethereum and DAPPS What is Ethereum? Introduction to Ethereum and DAPPS. So what is Ethereum? Ethereum is one of the largest and most well- established blockchains and it's based on the proposal from Vitalic Buterin in 2013. It was publicly available in 2015. Since it is open source, it's very easy to use it for private blockchains. Ethereum is not just a platform, but also programming language running on a blockchain so we can build and publish distributed application called DAPPS. Ethereum has its own crypto currency called Ether that in many ways is similar to Bitcoins. One benefit with Ethereum is that it has very fast transaction times where the block time is set to a few seconds as compared to minutes for Bitcoin. This can make it more suitable for applications where you need fast response, for example, checkout payments and rapid workflows. Another big thing about Ethereum is that it has a method for funding transactions depending on their computational complexity, bandwidth use, and storage needs. This is difference from the Bitcoin blockchain where transactions compete equally with each other. This means that you can pay to get faster transactions. We'll discuss this more later. The proof of work that other blockchains is using has had some negative impact where there are large computing compasses solving hard problems just to prove that they put work into it. This is a big waste of resources and Ethereum is moving more towards proof of stake where they use direct economic stake instead of proof of work. With all the fuss around Bitcoins and other blockchains to choose from, you'd probably ask why I want to use Ethereum as the base for this course. It really comes down a few reasons that you should also consider when you select the blockchain implementation you would like to use for your applications. First of all, the Ethereum development community is really growing and it's very easy to find resources and tools for rapid development. With emerging technologies like blockchain it's important to consider how well the community is adapting the different implementations and to be honest, the Ethereum community is really awesome and it's easy to get help from them. Ethereum has learned quite a bit from the Bitcoin development as well and it's by many considered to be an evolution of this. It really targets application development well with an easy-to-use contract language. Later in this course, we'll be spending two modules working with this. It's also rather easy to set up your own private blockchains and test implementations. Ethereum also has a broad commercial adoption, especially at the enterprise level and it fits well into enterprise solutions and existing architectures. Ether is the currency that is used with Ethereum. You can use it like any other crypto currency and it's the base for paying for transactions in Ethereum. It's traded under the ETH symbol and there are many ways to trade Ether. My current favorite is to use, which is a very simple solution to get started. If you consider to invest in Ether you should understand that this is a very volatile currency, at least for now. Ether has seen some really big ups and downs and it's not uncommon that it fluctuates more than 20% on a weekly basis. You should be very careful about investing, but if you have money to spare, investing in Ether can be a very good investment over time or as with any crypto currency or new investment possibilities, you could end up losing everything you have invested. Like all currency, Ether also has denominations to make it easier in daily use. Currently there are 12 denominations and they are generally given names inspired by those who have been a big influence to Ethereum. The currently smallest use denomination is WEI and 1 ETH is 1 quintillion WEI. Finney is also quite often used and 1 ETH is 1000 Finney. Szabo has of course also gotten its own denomination and 1 ETH is 1 million Szabo. When denominations get larger than 1 ETH we use Kether where the K stands for kilo, meaning that that 1K ETH is 1000 ETH. The same with Mether where the M stands for mega, Gether meaning giga ETH, and so on. When talking about Ether, you should also be aware that there exists something called Ethereum Classic that is traded under the symbol ETC. The reason it exists is because of something called a DAO Hack. The DAO is a decentralized autonomous organization that is funded on the blockchain. They have a crowd funding contract on the Ethereum blockchain and were able to raise a large sum of money and fortunately there was a weakness to the contract that made it possible to create a sub DAO and drain funds from it. After a while there was a vote in the community to make a hard fork at the blockchain, essentially putting all the funds back as they were at the time of the hack. This is a good example of the community coming together to solve a problem, but this also leads to a basic question. Is it okay to do changes as long as the code did exactly what it was supposed to do? There is a subgroup in the cryptology community that can be called crypto-anarchists and they believe that as long as code does exactly what it was supposed to, it's tough luck if you make any mistakes or subject yourself to being hackable. The vote to create a hard fork showed that most of the community disagreed with this, but it will be very interesting to see what will happen the next time something similar happens to the public Ethereum blockchain or other blockchains for that sake.

  13. The Enterprise Ethereum Alliance As mentioned, the Ethereum blockchain has a broad enterprise support and in 2017 the Enterprise Ethereum Alliance was created. Appearing on the slides you are seeing the logos of the launching members of the alliance. Their goal is to build and support the Ethereum blockchain. Their mission statement is as follows. Learn from and build upon the only smart contract supporting blockchain currently running in real-world production to define enterprise-grade software capable of handling the most complex, highly demanding applications at the speed of business. Wow! That was a mouthful, but I guess most mission statements are. Your take-away from this should be that the Ethereum blockchain is at least something that has a lot of major players investing into it and a lot of companies willing to support it.

  14. Distributed Applications (DAPPS) Let me just quickly introduce the concept of distributed applications. We will go into this into much more detail in later modules. In a traditional application architecture we could have a service setup that would provide the application in storage, data logic, and user credentials. A client would run an interface of some kind and these would have a set communication channel. With distributed applications on the blockchain, this can be constructed a bit different. Shared data is available on the distributed blockchain and exists in many locations so it doesn't matter if one of the servers goes down. The same applies to the data logic where the logic is shared on the blockchain. So as soon as you upload a contract to the chain it will spread and execute the same regardless of where you run it from. The client in a distributed setup also looks a bit different, since it will be responsible for storing its own user credentials and typically store more of the application data. Building applications this way will make your solution very resistant to system failure and it means that they can fully operate without a centralized system. You can still have functionality in the client for updates towards a centralized system, but you should ensure that your client does not rely on anything centralized. When deploying code to Ethereum we will create smart contracts built in a language called solidity. Let's spend some time looking at what smart contracts mean in the context of Ethereum. Smart contracts are pieces of code that live on the blockchain and execute commands exactly how they were told to by a shared logic. The contracts make up what will be the data logic for our distributed applications. They can read other contracts, make decisions, send Ether, and they can execute other contracts as well. Contracts will exist and run as long as the network. They will only stop to run if they run out of transactional funding or if they were programmed to self-destruct.

  15. Payment Model - Gas In every distributed system design it is crucial to have a well- functioning model for protecting the system from unwanted attacks. A general principal should be to make it harder to attack than to defend it. It's hard to do in the physical world. Just consider protecting a building. It's very expensive to put up protection and 24/7 security; however, it's quite inexpensive to build a bomb that will destroy the building. In the digital world this can be done differently. Just consider using hashing algorithms. They are inexpensive to use, but they're very expensive to crack. When protecting the blockchain against unwanted behavior, we want to use a payment model that will be fair priced if you use the system as intended, but very expensive if you try to do malicious things to it. This is where the concept of gas comes in. Gas is the internal pricing for running transactions or contracts in Ethereum. The reason for this is to have a unit that is separated from the current value of Ether. Just think about it like you would for a car. The amount of gas it uses is related to how fast you want it to go and the price of gas goes up and down and it's not statically linked to the value of the currency. The amount of gas that a contract or a transaction uses depends on the operations needed to run it. Their price is based on computation, memory, bandwidth, and storage needs to mention a few. These factors are added together and will make up the gas needed to run the contract or transaction. If you do not have the Ether to cover all the gas requirements to complete running your code, the processing aborts and all intermediate state changes roll back to the pre-transaction snapshot. The gas used up to the point where execution stopped were used after all. So the Ether balance of your account will be reduced with the price for the gas already spent.

  16. Transactions The term transaction when used in Ethereum needs to refer to the data package that stores a message to be sent from an externally owned account to another account on the blockchain. A transaction contain. The receipt of the message, a signature identifying the sender, a value field which is the amount of WEI to transfer from the sender to the recipient. A gasprice value representing the fee the sender is willing to pay for gas. The higher price you are willing to pay, the higher miners will rank your work. There's also a startgas value representing the maximum number of computational steps the transaction executed is allowed to take. Think of this as a measurement of the gas tank of a car when fully filled. This would be the maximum cost and it will make sure that you are not able to start infinite loops in your code. It is also important to the miner to get an estimate over how much they can earn by doing the transaction. Since the only way for them to know for sure is after the execution. Since an out-of-gas exception is practically a waste of money for a sender, it is always better to overestimate the startgas a little bit than to underestimate, but you should be careful of setting a too-high value as well because miners might penalize transactions where there is a big difference between the startgas and the actually consumed gas. You also have an optional data field which can contain the message sent to a contract. We will look more into this when we start to develop our own smart contracts.

  17. The Effect of Startgas and Gasprice Okay, now let's have a look at the effect of setting the different levels for startgas and gasprice. If you set the startgas to too low the transaction will probably not be sent to miners and you will get an intrinsic gas too low. The same is true if you set a too-low gas price. Miners will ignore the transaction and rather select transactions they can make money on. Setting gasprice too low is a bad idea since you will be getting an out-of-gas error and the transaction is rolled back, but as mentioned, you'll still be charged for what you have used so far. If you set a low gas price the transaction might be mined slower and put in a later block, depending on the current load of the miner. Medium startgas and gasprice is generally the ideal level and where you should try to aim. I'll show you how to estimate this later in this course. If you set a startgas too high, it might result in a delay of getting mined since the miners will think that it will need a lot of resources and must wait for availability. Setting a high gasprice will in most cases result in your transaction being prioritized and put in a block sooner than other transactions. Each block has a gas limit set to it. If you exceed that with your startgas, the transaction will not be broadcasted to the miners and you will get an exceeds block gas limit error. If you set a too-high gas price and the sender does not have enough funds available, the transaction is not broadcasted to the miners either. At this point I am sure you are a bit overloaded with information about prices and calculations, but don't worry. This is really not that bad in reality as you will learn later. So just remember the core ideas and you will be fine for developing with Ethereum. Proof of work is the mechanism that works with Bitcoin, the current version of Ethereum and many other blockchains. As I mentioned in the beginning of this module, this mechanism has been criticized for the environmental damage and electricity costs associated with the mining process. Some mining operations also use environmentally unfriendly energy sources. Just to put some aspect to this, the Bitcoin proof of work mining is set to consume the same amount of electricity per year that is consumed by a while midsize European country. In proof of work, a person might take $10,000, use it to buy a mining computer with specialized hardware and start participating in the network. The mining will then be producing blocks and getting rewarded for the work in the firm of crypto currency that can be spent. Proof of state attempts to resolve these issues by removing the concept of mining entirely and replacing it with a different mechanism. In proof of stake, one could take the same amount of money and convert it into crypto currency straight away. As with proof of work, the more you put in, the more you can expect to get out. In the time of recording this module, this is currently not implemented for Ethereum, but it is expected to be that at the later stage so I just wanted to make you aware of the thoughts around this.

  18. Ethereum on Microsoft Azure Now let's get into the real fun and start to look at implementing Ethereum. There are many ways to set up and work with Ethereum and in this course we will be focusing on working with Ethereum on the Microsoft Azure platform. Azure is a cloud platform from Microsoft and by using it we can also quite easily leverage the other aspects of the platform as well. This includes application hosting, storage, identity management, and security to mention a few. A consortium in the context of Ethereum means a collaboration between supporting members of a blockchain with underlying infrastructure. This could for example be a set of organizations that would like to work together and form their own privately shared blockchain. It all starts with the consortium leader. This is the controlling part of the blockchain where you set up the configurations of the chain. This includes creation of the Genesis block and initial allocations of Ether to the default account. One important thing to note is that when we are setting up a consortium, this will be a private blockchain that is isolated from the public Ethereum blockchain. Ether from a private blockchain cannot be exchanged directly with Ether from the public blockchain. After the leader is set up, additional members can join in with their infrastructure. We can control who can join our consortium and we also decide how we will share the available Ether. There are also a lot of ways to set up the infrastructure, but with a default Azure templates you'll get a baseline infrastructure that would work well in most situations. Let's look at it in detail and see how it works in a running scenario. A user will connect to a publicly available server for applications and administrative pages run. This must be set up as a separate instance. You should also consider if your client could be set up as a fully distributed application where the client runs on the user device. The application server is set up so that it can make a call into a virtual private network where it will hit a load balancer that will make a call to one of the many transactional nodes. With the default template, those nodes that are handling the transactions are isolated from the mining nodes and the mining nodes are not accessible from outside of the virtual private network. This is really all you need in order to create and operate a blockchain and since all of this is templated in Azure, you don't need to spend time setting this up. It will be done automatically for you. If you decide to add a consortium member as well, they will form their own virtual private network and make a tunnel between the VPNs. This also means that if you like, you can host applications on the member networks as well.

  19. Demo: Azure Account Setup Now we are finally ready for some demo action. Let's set up a blockchain consortium on Azure and we will let Azure create our Genesis block, filling it with some Ether for us. And to prove that everything works great, we will transfer some Ether between our newly created accounts. The first thing we need to do is to set up an Azure account. If you already have one, you can go ahead and skip this section. We will start at and click on start free. This will give us $200 or 170 EU that we can play around with for 30 days on Azure. I will click to sign in with my existing email address at Blockchain Rebels. We need to fill in some information here and as a security measurement for myself, I'll not show you what I enter in this video and I'll skip to the end of the visit shortly. You will need to have your phone and a valid credit card available for identification purposes. They will not charge anything to the card unless you explicitly transition to a paid offer. Okay, now I'll skip to the part where identification steps are completed and I'll click on sign up. At the top of the screen you will see a link for the portal and clicking this will bring up our dashboard.

  20. Demo: Ethereum Setup At the top of the dashboard we will click on the new button to create a blockchain consortium from scratch. Enter Ethereum in the search box and click enter. This brings up all the Ethereum relevant templates we can use. We will select the Ethereum consortium leader. You should be aware that these templates are under constant development so the name might have changed a little bit over time. We'll keep the deployment model suggested and click on create. Since the template consists of several different images and setups, we can create a resource prefix so that it is easy for us to keep these items separated. We will use the prefix bcl for now. The VM username is what we will use when connecting to our nodes. We will keep it at gethadmin. We can select between SSH public key, which is the safest or using a password for authentication. To keep it simple, we will use password for now. If you are going to use this for production, you should of course set up a paid subscription, but for this course we will continue to use the free trial subscription. A resource group is a collection of resources that share the same lifecycle, permissions, and policies. To keep things tidy, we will create a new resource group called blockchain. You should select the location that is closest to where your solution will run. I'll select the Northern Europe and click on OK. Since we can have many members of a consortium, we differentiate them by an ID. Since we are creating the first part of our consortium we will keep it at zero. You can select the number of mining nodes you want and this can be up to 15. We'll keep the minimum now which is 2. Depending on the use of the chain, we should consider what type of storage we will use. Basically, the difference is that you get a much higher disk I/O with a premium since that option will use solid state disks instead of the standard magnetic drives. We must consider how we want the storage for our nodes to be replicated as well. We will keep the locally redundant storage but we could also select that we would like the storage to be geo redundant. You could argue that this does not make much sense in a large consortium where the nodes are at different locations anyway. We can then select what kind of resources we would like to have for our mining nodes. These have a big range in both price and performance and there is a lot to select from. If you click on the line you will see an estimated price for each of them. We will keep the standard D1 v2 for now. Now we must make the same consideration for our transactional nodes. We will keep the default setting where we will only get one transaction node. It is now time to set the Ethereum-specific settings. The network ID can be considered the name of the Ethereum network we will be setting up. Only nodes that share the same network ID can pair with each other. We will keep the default here as well since it is easy to remember. ID up to 10 should not be used since it is in use by the public Ethereum. If we want, we can also provide a custom Genesis block here. This is for example useful if you want to set an existing account to be used for a default account or default settings for the chain. We want Azure to create a the Genesis block for us so we keep the value. We must, however, set the password that will be used for the default account. It is important that you remember this password. To generate a private key for the Ethereum account we need to provide a passphrase. I'm going to enter a simple one here, but you should really use an online generator for this and save it somewhere safe. Let's review that everything looks good and click on OK. As always, it is important to read the agreement and terms of use before you click on purchase. Now it will take some time until the deployment is done, but I'll edit out the waiting time for you. There we go. The deployment is now complete. Let us have a look at the deployment by clicking on the resources in our dashboard site.

  21. Demo: Ethereum Deployed Then we select deployments. To get to the page where we will find the information about our blockchain we select the Azure multi-member. Here you will see everything you need in order to connect to our chain. We copy the address for the admin site and open it in a separate tab. At this page you will see some information about our blockchain. Azure has created a Genesis block for us with a default account that is listed here. As you see, we also have quite a bit of Ether to get our blockchain started. Let us set up a second account and transfer some Ether from the default account. First, go back to the Azure tab and click on the copy link to the Ethereum RPC endpoints. We are now going to use a wallet application called MetaMask. It's a really good wallet application for development and testing. MetaMask is an extension to Chrome so we will need to install it first. We click on the upper right icon and get to the settings. Here we must click on extension and we will scroll down to get more extensions. We will search for MetaMask and click on add to Chrome. You should now see a fox icon in the upper right corner. Read the terms of use and click on continue. Enter a secure password that you will remember. It will then create a set of words that you can use to restore all your accounts. You should keep this safe, especially if you're going to use this for real Ether. We are now connected to the Ropsten Testnet and as you see, we're given some Ether to test with. Unfortunately, this is also only for testing so we cannot exchange it for real Ether. We will now connect MetaMask to our newly created blockchain and we do that by clicking on settings. Here you will paste the URL that we copied earlier and click on save. MetaMask will now refresh and as you see, we are now connected to our blockchain. If you look at this, our account now has zero Ether in this chain. We will now use the admin page to transfer Ether to our account. So we click on the copy symbol to copy the address to our newly created account. After that we go back to the admin tab. We scroll down and we paste in the address. When we click on submit, we will send 1000 Ether from our default account to our newly created account. If we open MetaMask now, we should see some Ether coming in quite soon. Wow! Fantastic! As you see, our transfer is complete and our blockchain is confirmed to be working. We are now ready to start developing with our blockchain.

  22. Summary In this module we started by discussing the what and why of Ethereum. We looked at the execution and funding model of Ethereum before we went into distributed applications. Then we finally started to look into an actual implementation template and the resulting infrastructure. After that we finished by creating our own blockchain on Azure using the consortium leader template. Making money is fun so we transferred our freshly made Ether between our accounts. Now in the next module I will show you how you can set up your test and development environment with ease. I'll make sure not to skip anything so that you can follow the rest of the course by doing coding and configuration alongside me. I'll see you there shortly.

  23. Setting up the Development Environment Overview Set up of development environment. The purpose of this module is to show you how to install and configure the development environment from scratch. With blockchain development it's hard to find the setup that really works so I want to make sure that you don't have to research this yourself in order to get started. During this module we will install Chrome. This will be our default browser. We will need to install MetaMask as well which is an in-browser plugin that will help us immensely with the authentication and running of our applications. Visual Studio Code is a free and easy to use version of Visual Studio that is excellent for blockchain development. We will install two different package managers that will make it easy for us to get the components and tools we need. The first being NodeJS Package Manager or NPM for short. The second is Chocolately. GIT is the source repository system that we will use together with NPM. Some of the tools we will be using will require us to build them so we will need the Windows Build Tools as well. To test our development we will use a local in-memory test server called Test RPC. Lastly we will install Truffle. Truffle is a framework tool that we will spend quite a bit of time on during this course and I'm sure you will really like it.

  24. Install and Config I'm starting with a clean Windows 10 image that I've created on Azure. You can do this as well if you like or you can follow the installation on any supported O/S. So let me switch over to the fresh machine and we will get going with install and configuration. As mentioned, this is a fresh install of Windows 10. The only thing I've changed is the background. The first thing we want to do is to install Chrome. As normal, when downloading software we get a security warning. There, it is installed so let's go ahead and make it default. Now the next thing we want to do is to install MetaMask. MetaMask changes quite often so in order to make sure that you'll be able to run the demos in this course, we will use the 3.5.2 version of it. MetaMask can be downloaded from GitHub at the following address. We will go to the MetaMask plugin, releases, and somewhere far down we will find the 3.5.2 release. As you see, there are plugins for all the popular browsers. We will select the one for Chrome. Let's unzip the file and go into the settings. Here we navigate to extensions and we enter developer mode. We click on load unpacked extension and we select a folder where we unzipped the MetaMask plugin. There we go! You should now see a fox icon in the upper right corner. We can now disable the developer mode again. The next we will install is Visual Studio Code. This is done from And we will download the latest stable build. For this setup we want to use the default settings for all the screens. There we go. We just unclick the launch Visual Studio Code and click finish. Next in line is NPM, the Node Package Manager. And again we will download the latest version. And also with NodeJS we want to keep all the default settings. That was the first package manager, now we go for the second one, which is Chocolatey. We will have to install that by using PowerShell and we get the PowerShell scripts from the page. Just copy the line with the script from this page. You can now close Chrome and open up a PowerShell as administrator. I recommend that you add it to the taskbar since we will be using it quite often. To be able to run scripts, we must ensure that we don't have a too restrictive security policy. We will therefore change the execution policy to remote sign. This allows us to run the scripts we need. And we want to say yes to all. Now paste in the install script for Chocolatey. To get software from the open source repository on GitHub we will install the GitHub client and we will do that by using the Chocolatey install command. You should also note that this installs other useful tools as well like the secure shell client that we will be using in this course. We get asked if we want to run the script and we answer yes. Now we will close and reopen PowerShell. This will ensure that everything is refreshed after installing. Remember to open as administrator. To avoid any issues with security we're also going to turn off the feature in GIT that requires all calls to be secure. Now we will use the NPM to install the node add-on build tool. Next we do the same with the Windows build tools. In order to test our solutions we will also install a local Ethereum test server called Test RPC. Don't worry if you're getting some warnings along the way. And the last thing we need to install with NPM is the Truffle toolset. That's it. You are now ready to start developing.

  25. Summary and Links To make it easy for you to find all the tools you need, here is a list of all the download locations we went through. And here is also all the PowerShell commands that we ran. Now you should hurry to the next module in order to get started with your development.

  26. Understanding Smart Contracts Smart Contracts Basic Blockchain fundamentals, understanding smart contracts. Making a smart contract is in many ways quite similar to what you might be used to already. You start by writing the code in a supported language. That will be different depending on the blockchain implementation you are working towards. In this course we will be using a language called solidity, which is supported by Ethereum and it's currently gaining support in the Bitcoin blockchain as well. Another current option would be to write Serpent code, which also has some community support for Ethereum. After writing the code it must be compiled to byte code. There are several compilers available. There are even online compilers that will get you started quickly. In this course we will use a framework for working with smart contracts that is called Truffle. Truffle has a built-in compiler that is very easy to get started with. When a compile is done successfully, we upload our contract and wait for it to be mined. After the contract is successfully mined, we can start interacting with it. In most cases you would create a user interface towards the contract, but you can actually interact directly with it through http post operations. So let's talk a little bit about the tools that we will be using in this and the next module. Firstly, the language. Solidity is an object-oriented JavaScript- style language. The idea for it came from Gavin Wood in 2014 and it was developed by the Ethereum project Solidity team. If you have programmed with other object-oriented languages before it's quite easy to get used to. Solidity has the possibility of a normal inheritance as well as multiple inheritance and you will find the supported data types and coding structures quite familiar. Here we are seeing a very simple example of a Solidity contract. We will look into the details of the most used parts of the language in this module. I will not go through all the different data types that is supported by Solidity, but let me name the most used ones to get you started. Booleans are supported with the keyword bool and it can contain the constant values of true or false. Strings are also supported and are encapsulated with quotes as you are probably used to, but string manipulation is currently very limited and it really should be. This is to underline that you should really strive to do the most unnecessary work outside of the blockchain. Integers can be signed or unsigned and they range from integers from 8-bit resolution to 256-bit. In an 8-bit integer you can store integer numbers from 0 to 255. In an int256 you can store numbers from 0 to 2 to the power of 256, which is a very, very, very high number. You should be aware that if you don't give a size to the integer and only use the int or uint keyword, the maximum size will be used. Another really useful type is the address type. It can store an address used in Ethereum, for example, to an account or contract. This is useful in many ways as we will see later. At the time of writing, Solidity does not support fixed point numbers, but it should be supported quite soon. When using the upcoming type you must specify the number of bits you want to use for each part of the number, for example 8x8. In the current version of Solidity, you can work with decimal numbers and do calculations, but fixed point results must be returned as truncated numbers or integer arrays and this again is really to underline the fact that you should really do only the most necessary things on the blockchain. Everything else should be kept outside. As with most other programming languages, we have access modifiers. Access modifiers are keywords used to ensure that your code only can be executed from where you expect. Public means that it can be accessed from everywhere. Private limits access only to this contract. Internal means that this contract and those contracts deriving from it can access the method or property. External will disallow internal access and make it only accessible externally. One important note though. Everything that is inside a contract is visible to all external observers. Making something private only prevents the other contracts from accessing and modifying the information, but it still will be visible to the whole world outside of the blockchain. Here is an example that encapsulates some of the main structures of Solidity. Firstly, it's defined by using the contract keyword and the name of the contract we are using. Within it we can have state variables and functions. Functions that return values define the return type. You should also be aware that you can have multiple return values in Solidity. Here we see that we have used the public keyword. This means that the function is accessible from all locations. Public is the default so in this case it's really not necessary to define it, but I like to make it clear in order to avoid any unintended behavior due to my neglect.

  27. Truffle and Test RPC Now let's talk a little bit about Truffle. Truffle is a toolset framework for development, testing, and as a pipeline for Ethereum development. Truffle includes tooling to compile and build your solution. It enables a framework for automated testing, and it makes deployment of our contract very simple with support of configurable deployment locations. Another great thing about Truffle is that we can actually use it in console mode as well in order to interact directly with our deployed contracts. This is quite cool and I'll show you how it works shortly. When working with smart contracts it is crucial that we know that our contracts really work as expected before we unleash them to the world because we don't have a feasible option for doing a take-two. Uploading to a blockchain test environment on the net will take some time. It is therefore very timesaving to use a local test blockchain instead. Test RPC is an easy-to-use in-memory blockchain that is great for testing your contracts while developing. Not having to wait for an external blockchain will really speed up your development in the early phases. Test RPC implements Ethereum JS which is the same set of instructions that you'll find in the real Ethereum blockchain. Another great thing about Test RPC is that it will automatically create 10 throwaway test accounts for you with the connected private keys.

  28. Hello World Demo Let's see how this all works in a quick demo. I'll fire up TestRPC, create a project with Truffle from scratch, and as with all introductions to a new language, we will make a simple hello world contract. Let's start by opening up a new instance of Windows PowerShell. We will create a folder for our demo by using the mkdir command. We will call the folder demo and create a subfolder called hello world. Use the command cd to go into the demo hello world directory. We will now call on Truffle to initiate our solution. This will create a simple framework for us that will let us get started quickly. There. The solution framework is created. Let's open it up in Visual Studio Code. We open it with the current directory by entering the command code dot. If we look at the explorer we will see that it has created some test contracts for us. We will leave these extra files there for now. Let's click on the contracts and add a file called helloworld.sol that will be our contract file. The first we want to do is set a pragma telling the compiler which versions of Solidity our code will work with. This is very important since we are really reliant on having our code execute exactly as expected. We will set it to work with any version about 0.4.4. Then we will create our contract called hello world encapsulated by squiggly brackets. We will then create a function that is called say hello that returns a string. Inside the function we will return the string hello world. Now hit Ctrl + S to save the file. The next we need to do is to edit deploy contracts. You will find it under the migrations folder. This is the file that will tell Truffle which files to deploy to the blockchain. We will create a variable called hello world that links to our newly created artifacts file. We must then add the variable to the deployers. Hit Ctrl + S again to save the file. We will now start TestRPC server to get our own blockchain running. We do this by opening up a new instance of PowerShell.

  29. Demo: Deploy and Test Enter the command testrpc to start the server. When starting, it creates a set of test accounts and private keys. The first account is what is used as the default account. By default, the server will run at localhost port 8545. Now that we see that it is running, we will go back to the other PowerShell we opened up earlier. We will now compile our solution by using truffle compile. The solution is now successfully compiled and we are ready to deploy our contract to the blockchain. That's done by using the migrate command to Truffle. There our contract is now successfully uploaded to our test blockchain and you can see the address it got when uploading. We could now go ahead and create a user interface for our contract and test it out, but with Truffle there is also the option of communicating directly with it. This is a very easy way to run the contract so we will use the command truffle console to get started with Truffle in console mode. In console mode we are actually able to write JavaScript code directly towards our contracts. This takes some time to get used to as your commands will be executed as code line by line. Let's define the variable called hw for easy access to our contract. Since it is not defined with the content yet, we get a response saying undefined. This is not a halting error, it's just information for us at this point. Then things get a little bit complex. Since working with contracts should be done async, we must use async code to access our contract. The contract is referred by using the deployed keyword so we will access it with the helloworld.deployed. We then use the then keyword to create an async function that will map the deployed contract to our previously created variable. We can now access our contract and methods directly on the variable. Let's try it out by using the call function of our hello method. And there you go. Our first program is running on the blockchain. What a fantastic feeling! Let's return to the slides for a while and see what else we can do with smart contracts.

  30. Advanced Types Let's spend some time looking into more details of Solidity. We start with structs. Structs are custom defined types that can group several variables like in the example here where we are defining some variables on a person structure. Structs can also contain other structs like you would expect. Enums is short for enumerated types and can be used to create custom types with a finite set of values. This can really make your code easier to read, but you should be aware that when your return an enum it will actually only return the integer value associated with it. Arrays is a data structure that contains a group of elements. These elements must be of the same data type. Arrays can consist of native types like string and integers or they can consist of more complex types like structs. Arrays can be dynamic like the two top example or they can be of a fixed length as shown in the last line. Arrays are assigned or read by using the index of the element you want to access. For arrays and structs you have additional annotation that will set the data location. Data locations change how assignments behave. Depending on the context, there is always a default, but it can be overridden by appending a keyword to the type. The default location for function parameters including return parameters is memory. The default for local variables is storage and the location is forced to storage for state variables. The third data location is calldata and this is a non-modifiable, non-persistent area where function arguments are stored. External functions input parameters, but not with current parameters are forced to calldata and for all practical purposes for us it behaves like memory. Mappings is a very usable structure that we can use as well. A mapping will map any type to the index of another type. A very common use for it is to map addresses to values like in the example here where we have a list of currency balances for an array of addresses. When accessing it you use the type define to access it. If you are used to writing C# you can think of mapping tables as dictionaries. The only possibility that the code is removed from the blockchain is when a contract that address performs the self-destruct option. The remaining Ether stored at address is sent to the designated target and then the storage code is removed from the state. Using the delete keyword is a good way to clean up a contract and delete all stored data for the variable. This is a little less drastic that will self-destruct the entire contract. If condition checks fail or something goes wrong in your code, you can use the throw command to stop all operations. This will return the Ether that is not already spent to the caller. Using conditional throws is a much more recommended way to stop your contracts from working than to use the self-destruct option. One way to do this would be to implement a bool as a private state variable in your contract base and use throw if it is set. This would keep the contract in place and keep data already stored intact, but render it useless for new executions. Comments are supported in three ways. You can use double slashes for single line comments. We use /* for multi-line comments, and Solidity even supports the use of Natspec type of comments. These are marked with three slashes. We will not go into the detail of this now, but with this type of commenting you can for example generate metadata for your contract facades.

  31. Demo: Storage Now let's try out some of these possibilities. In this demo we'll create a simple storage contract for Ethereum. And we will deploy it for running private Ethereum implementation. We will start back in PowerShell and our demo directory. In this demo we will be making a contract for keeping game scores so we will make a directory named score store using the mkdir command. Now let's initiate our project with the truffle init command. Once that's done we open the current folder in Visual Studio Code. Now we will create a new contract file called ScoreStore.sol. As always, we'll begin by setting the pragma for Solidity so that we know exactly how our code will be executed. Then let's make the frame for the contract. To store scores we will be using a mapping variable that maps strings to ints and we will call it person scores. Now we need a function to a person to the score. I'll call it add person score and it doesn't need to return anything. It should take a name as a string and starting score as an int as parameters. Inside the function we want to add the values to the mapping variable. If we leave the code like this it will work, but if you by accident add the same person twice, it will nullify the score. To avoid this we make an if statement to check if the value is larger than 0. If not, it will throw an error. Next we want to add a function for checking the score of a given person. We'll call it get score and it takes the name as a parameter and returns the score as an int. This method can return directly from the mapping variable. Hit Ctrl + S to save our file and this should cover the functionality we want for this contract. We now need to go into the deploy contracts file and add the score store contract to the deployments. First we need to get the artifact for it at the top of the file. Then we want to add it to the deployer as well. To avoid uploading the sample files that were created by Truffle, we will just clean up the variables and deployers a bit as well. Go ahead and save the file and we'll also delete the same contracts as well. Ensure that you have saved all the files and we go back to PowerShell. Let's start to compile using the truffle compile command. There we go. If you don't have the TestRPC running already you should go ahead and start it now. Let me use the migrate command to upload to the TestRPC. Everything seems to have gone well, but let's use the console to ensure that our contract works as expected. To make it easy for us to use the contract, we'll make a variable for it called ss and add an async handler to it. Now let's try to add a person to our score store. And let's make a call to the get score method to see if it got stored. That seems to work great and we are getting the score back. Let's try to add the same person once again to see if it throws an error. Great! The code gave an exception and stopped executing, just as we wanted. Now that we know that our code works, it's time to publish it to a real blockchain. We will use the blockchain we created in a module earlier. To do that we need to do a few steps. First, let's close PowerShell and go back to Visual Studio Code. If you look at explorer you will see a file called truffle.js. This contains the definition to the deployment locations. As you see, there is a location defined for our localhost environment. We want to copy this and create a new location called production. We now need to get the address to our production blockchain. To find it we go into the Azure portal and find the deployments page for our blockchain. At the deployments we will look for the Azure blockchain. Usually you will find it on the top of the list. Here we want to copy the address to the Ethereum RPC endpoint. Let's go back to Visual Studio and copy the value to the host portion of our settings. We must also remember to remove both the http part of the values as well as the port number since this is defined in a separate setting. Notice that the port number is already set to 8545 so we don't need to change it. Hit Ctrl + S to save the file and start a new PowerShell. Go into the project directory by using the cd command. We need to compile our solution again by using the truffle compile command. When migrating to our production network, we must specify the network name we just created as a parameter to the migrate command.

  32. Demo: GETH and Unlock Account There. We got an exception from the deployment. The reason for this is that our blockchain is protected from unauthorized changes by default. Our blockchain is at this point in the early stages so we haven't even added users beyond the default account. To administrate our blockchain we can use a tool called geth and that can be run from one of the nodes in the network. To connect to this, we will use a secure shell client called ssh. To find the address to our node, we go back to the properties page on Azure. This time we want to copy the value from ssh to first tx node. This gives us all we need to get into our transaction node. Copy it and we open up yet another PowerShell. Paste in the command and hit enter. It warns us that we can't be sure that the host we are connecting to is authentic. We'll accept the risk at this point and enter yes. Now you will need to enter the password that you provided when creating the blockchain. There. We are now connected directly to our transaction node and can execute commands. We now want to start a geth client and attach it to our blockchain. To do so we enter geth attach. Geth is a JavaScript console that enables us to send commands directly to the blockchain. What we want to do now is to unlock the default account so that we can do transactions with it. To do so, we use the following command. The eth.coinbase is a reference to the default account. Now you must enter the passphrase for the default account. This will be the same you provided earlier when installing the blockchain. Now our default account is unlocked, you should note that this will automatically be locked again so you might want to keep this console open while we work further in case you need to unlock it again. Go back to the other PowerShell window and we will try to migrate again. There we go. Our contract is now uploaded and running on our production blockchain. Now let's use our contract the same way we did earlier and check that everything is well. To get into the console mode for our production blockchain, we must use the network parameter as well. Again we will make a shortcut for our contract. Now let's make a call to the add person score. We will call it with a different name this time. And here you see that I made a mistake that you'll probably be making quite a lot yourself. Notice that I've used the call method and it really didn't do anything. In order to execute these types of calls, we really need to execute the command directly. So we will try this instead. There we go. It worked. So the difference between using the call method and making the direct call as I did now is that when setting variables we are using the direct call. When asking for return values we will use the call method to get the async handler back. As you might notice, transactions take a lot longer time on the real blockchain than on the TestRPC. So using TestRPC during development will save you a lot of time. Anyway, our transaction is now mined and we should be able to get the value back as well. To see the value that is returned, as I mentioned, we want to use the call method this time with the parameter we are calling with. There we go. Our score store contract is now running on a real blockchain and it's ready to use.

  33. Calling External Functions With Ethereum we can actually do external calling of functions as well. Let's say we have contract A and contract B. Contract B has some functionality that we want to make use of in contract A. With Solidity and Ethereum we can actually make a call from contract A to contract B. Let me show you how calling external contracts actually works. We will go ahead and create a second contract and we will call our first contract from the second contract. Let's head over to Visual Studio once again.

  34. Demo: Calling External Functions Now to show you how we can use contracts, I just want to make a very simple example for you so that you see how easy it really is. We will create a contract for a specific game that will use our score store contract to keep track of the game score by making external calls to it. Again, we have opened up PowerShell and we will create a folder called MyGame and again we will do a truffle in it and opening it in Visual Studio. Go ahead and make a new contract called MyGame.sol. We don't bother about deleting the sample files now, but of course you should always do that when going beyond these demos. Again, we will be adding the pragma and making the contract framework. We are now going to create an interface that will resemble the contract we made earlier. This is necessary in order to tell Solidity about the structure of the contract we will be using externally. We will call our interface IScoreStore. Our interface does not need to have all the properties and methods of the original contract, only those we will be using. We will only make use of the GetScore function so let's make a placeholder for it. After that we will create a method that uses the ScoreStore contract we deployed earlier. We named the method on our contract ShowScore and lets it accept a name. Now our method will work as a proxy for the GetScore function in the ScoreStore contract. We must now create an instance of our interface. We will call the instance ScoreStore. The interface accepts an address to our existing contract as a parameter. To find the address we open up our ScoreStore contract in console mode in the new PowerShell. By using the command scorestore.deployed we can find and copy the address to our deployed contract. As a note, it is generally a good idea to keep the address for our deployed contracts stored in a secured node as well. You can now close the window if you want and go back to Visual Studio. So let's paste the value as a parameter. We can now make a method call to the GetScore function and return the value. Hit Ctrl + S to save the file. Now we need to set up the deployment location to production. Again, you will find the value in the Azure portal. And as always, we need to add our contract to the deployments. I'll also go ahead and remove the other deployments so that we don't spend unnecessary Ether. There, hit Ctrl + S again to save and we will compile. As you remember, we also need to unlock the account to migrate so let's just quickly do that. You should note that in this demo as well you might experience that the account is locked even if you are doing exactly the same as me. If that happens, just go ahead and unlock the account and try the operation again, but anyway, let's migrate now. Awesome! Everything looks fine so let's see if it works in the console mode. Let me just quickly create a variable for the contract. Now we know that to get the value from the blockchain to the console we need to write an async handler. You are probably getting used to that now. Let me just show you one other way of doing it where we will actually create a function that logs directly to the console. Fantastic! We have now created a contract that uses another contract to do its work. Of course, this is a very simple demonstration, but it shows you how you can make use of the contracts that others have made as well.

  35. Summary In this module we have gone through the basic concepts of Solidity. We then did what we always do when learning a new programming language. We made our first Hello World contract. After that we looked at some important aspects like mappings and arrays before we created a contract that does blockchain storage and pushed it out to running blockchain implementation. Right at the end we made a second contract and I showed you how to do external contract calling. Now that we have looked at the basics, let's jump over to the next module where we will be creating a simple, but full application that lives on the blockchain.

  36. Sample Application: FoodSafe Introduction Sample application, FoodSafe. The purpose of this module is to make an end-to-end application with Ethereum, but before we get to that, we need to have a look at some of the front-end technology that we will be using. The Ethereum JavaScript API is what we have used already in order to interact with our contracts in console mode. This can of course be used directly in web pages as well and that is basically what we will be doing in this module. The Ethereum JavaScript API is available through the Web3.js and it includes functions for all the scenarios that you might encounter in your day-to-day development with Ethereum. Basically what it does is to make RPC calls under the hood for us. It is absolutely possible to write these codes yourself, but it is a huge time saver to use the API instead. It handles all of the tedious plumbing work and I would say that your usage scenario is very special or advanced if you would need to make your own RPC calls. The really great thing about this API is that it works together with the MetaMask application and makes all interaction with accounts and such really easy to do. By using the API and MetaMask, all the plumbing of authentication is done for us so we only need to consider who is allowed to do what, instead of having to figure out who the user is. Of course, the user in this case will be an Ethereum account and that account might as well be anonymous to us. Building an application with JavaScript can quickly become quite messy and hard to keep an overview over. We want to have our different parts of the solution in separated files to keep complexity down and to be able to make reuse of the files. There are many ways to deal with this, but Webpack is a module bundler that has gotten a broad community support because of its simplicity even in larger projects. The way Webpack works is that it will take all our assets through the module bundler and it will output files ready for execution by the browser or server.

  37. Demo: Truffle Webpack Before we really get started with our sample application, I just want to spend some time on showing you how to initiate and use the samples provided by the Truffle client. Start a development server and interact with the initial contracts. The first thing we need to do now is to create a folder for our test. We'll call that folder WebpackSample. Instead of doing Truffle in it as we've done before, we will add the Webpack parameter as well. This will now download and in it everything we need in order to use Ethereum, JavaScript API and Webpack. Don't worry if it takes some time to download all dependencies. Now let's open up Visual Studio and see what we got there. Let's first look at the contracts folder. Here you will see the MetaCoin sample. This is a sample contract that makes a simple coin that can be traded and sent. It stores the balance and has a method to get the balance of a specified address. If you look above the contracts folder, you will find a folder called app. This is where the application files are stored. The index.html file is a sample html page that lets us send MetaCoin to addresses and if you go into the JavaScript folder you will find an app.js file. In this file you will see some simple plumbing of Web3 and some functions that interact with the contract. Here we see for example refresh, balance, and SendCoin. Let's also look at the Webpack.config.js. This is the file that lets us set up the Webpack module bundler will work and for example, here we can see that it will copy the index.html file to the build folder that we will run from. Okay, so this was just a brief view of the sample code. Let's go ahead and start it and check it out. First we make sure that we run a TestRPC server just like we've done before. Then we want to compile and migrate. The last thing we need to do is to start up a development web server. We will use the command npm run dev to do so. This will host application for us. Note the address where the server is running. This might be different for your setup. Now open up a browser and navigate to our test server. You must also make sure that MetaMask is connected to the local server now. We also want to import the default account of our test server so that we have an account with some test Ether already loaded into it. To do so we must copy the private key for the account and use the import function on MetaMask. Okay, we click on the hamburger here and we click on import account. Paste in the private key string here and click on import. As you see, we have quite a bit of Ether to play with now. This account will also have the coin based balance for our MetaCoins. So if I refresh here now, we should see that we have 10,000 MetaCoins. So to do that in a simple transfer let's just copy the address to one of the other accounts and paste it into the address box of the application. Let's send 200 MetaCoins. This is one of the great things about using MetaMask. It will actually look for initiating transactions and when we do, MetaMask will give us an estimate of what it will cost us to run the transaction. This looks quite okay so we click on accept. After refreshing, you see that we have transferred away some of our MetaCoins and we only have 9,800 left. The reason I wanted to show you these before we build our own application is that these examples are actually quite good and shows off a lot of useful cases. So even though we're not going to go deeper into this now, I really encourage you to have a look at them yourself.

  38. FoodSafe Description Now we should be ready to get on with our sample application. We will be building a simple application that will make use of the Ethereum blockchain to store information about batches of food. We will call the application FoodSafe. The application will give an unchangeable track of the origin of the product as well as the trail it takes until it reaches the consumer in the store. To achieve this, we will make a Solidity contract and a simple web user interface. Of course, this is a sample application so we will only be able to scratch the surface or the functionality that you might want to implement, but we will make it work from end to end. One of the other areas we will look at is how to keep secret in the blockchain. In a food tracking scenario, the different parts of the supply chain generally want to keep some secrets from competitors during the lifespan of a product. Let's take production of a tomato sauce as an example. A producer wants to share information about, for example, specific tomato GMO identifiers with the supplier, but they want to keep it secret from other producers since it might be a business secret. The suppliers are in the same situation. They might want to hide information about the specifics of a producer from other suppliers, but they want to share it with the store. All of the participants in the supply chain must share all of the information with the government. The way we will handle this is that we will enable the possibility of adding secrets with a passphrase. Only those who know the passphrase will be able to read the secret, thus every part of the supply chain can choose who they want to share the passphrase with. Our application will support three different scenarios. First, for each new batch of products we will be adding a new contract to the chain instead of tracking all products with the same contract. This will be much more efficient and give us the ability to abandon contracts at the end of the chain rather than keep adding to large contracts. Secondly, our application will be able to write information to the contract. This will be information about the location and we will also add the ability to add secrets. The last scenario that we will support is the reading of information about the product batch. This will also enable you to read the secrets if you have the right passphrase.

  39. Demo: FoodSafe Contract Let's begin by writing a contract for our project and test it with TestRPC to see that it works as we expect. This time I've done exactly what I showed you in the previous demo but I've cleaned up the init files a little bit for you. The way I made it was by using Truffle in Webpack and I've deleted all the unnecessary files and even added the right migrations for you. You will find the project in the demo files for this demo and it's called foodsafe empty. Copy the files into a folder called foodsafe and open it up in code. I've prepared an empty file for the FoodSafe contract; let's open it up and get started. We will use this contract to store information about locations so let's create a struct for that called location. We want it to store the name of the location, the ID of the location. We also want to store the ID of the previous location. When creating a location trail it's also good to save the timestamp for the different locations. You should be aware that this timestamp won't be 100% accurate because it will be at the time when the block is mined, and lastly we will enable storage for secret for each location. Now we want to store the trail and for that we will be using a mapping. We will be mapping a location to a location number. To easily keep track of how many locations we currently we have, we will use a trail count. A uint8 should be enough. In these cases I also have the habit of explicitly setting to 0, even though it's really not necessary. Now let's make the function to add new locations. We will code AddNewLocation and the input should be a location ID, name, and secret. This function doesn't need to return anything. Let's get our inputs into a temporary object called new location. We will place the temporary object in memory for now. The location ID and we set the secret and to set the timestamp we will use the now function. And if the trail count isn't 0, we can set the previous location ID to the current location ID. Okay, so let's add the location to our trail and after we have added it we increase the trail count by 1. Let's also make a function that returns to current trail count and that will of course return a uint8. Last function we will be adding is a function to get a location out of a specific placement in the trail. We will call that function GetLocation. Since it's not a good idea to return arrays we will have to use multiple returns for this one. This one will be the location name, the location ID, previous location ID, timestamp, and lastly the secret. And then we can go ahead and return it directly from the trail. And lastly the secret. Now that should do it. Let's save and start up TestRPC. There we go. And we should now be able to compile and migrate. Perfect! Now let's open it up in console mode and check it out. And as you have seen me do a couple of times now, let's just make an easy access variable. Let's use the contract to add a few locations. Okay, let's make it not very secret for now. Okay, let's see how this works. Great! We've got some computation here. Let's add a couple more. And last one. Okay, so it seems like we've got this stored, so let's just call the GetLocation to see that we get what we expect. Let's see if we can get the first location now. There we go and the second location. Let's just see also that we haven't got anything for the location 3. There we go. All zeros and just for fun, let's also check the third location. Remember that these are now 0 bound so that's why we start on 0, 1, 2, and 3 for the fourth location, which is empty. There we go. We've got all the three locations and we even check that we didn't have anything on the fourth location. This means that our contract is working like we expected and it's ready to use.

  40. Demo: Compile and Upload Contract In this next demo we will use the Ethereum JavaScript API to create a new contract for each new product batch. To use the contract later we will get and store the contract address for it. Let's head back to Visual Studio Code. We will begin by creating a new function in our app framework to handle the creation of a new contract. The first we want to do now is to go into the app.js file. In our case we will be using MetaMask and this is the plumbing code to get the default accounts and the other accounts that are available from MetaMask. In addition to what is already here, we want to set a default account so that we don't need to do that for each call we will be making later. The first account that we are getting from MetaMask is the account that you're currently logged onto. Now for this project we are going to compile and send our contract directly to the blockchain via JavaScript rather than to use Truffle for this as we have done before. To be able to compile our contract we will use the solc compiler and in order to do so, we must first install it on our transaction nodes and as you might remember, the way to access the transaction nodes is via SSH. We'll get the SSH command from Azure as we've done before. And we'll fire it up in PowerShell. Still we are trusting this. Firstly we need to set the repository right and we do that by using the pseudo add-apt-repository command. And we want to set it to the Ethereum repository and we add the Y parameter for yes so that we don't get any questions now. Next what we want to do is to do an update. Now that that's done we want to do the actual install of solc. And if you haven't figured it out all, solc is the Solidity compiler. There we go. We can now go ahead and close PowerShell. Okay, let's continue on our plumbing code. For our contract we need to get the definition of the FoodSafe contract into a variable. There are many ways to do this, but one simple method is just to make it fit on one line by removing all the line breaks. Let's just go ahead and do that for now. There we go. The contract is now on one line and we can go ahead and copy it into our plumbing code. We'll call the variable FoodSafeSource. Now that we have the source we can go ahead and compile the contract and we use the Solidity compiler. We give it the source and we provide with a callback function. This callback function will take in a variable for error and also the compiled FoodSafe contract. The next we need to do now is to get the FoodSafe ABI, the Application Binary Interface. And to access the compiled contract, we actually need to use the full name of the compiled contract. This will be different from the TestRPC to other Ethereum implementations, so be aware if you get an error at this point, it might be that you haven't used the correct full name for it. And we go into the info for the contract. And the ABI. The application binary interface is what we'll be using to create our contract. So we will make the actual contract and as you see, we use the ABI as a base for the contract. The last thing we want to do is to get actual binary code from our compiled contract. To the observant watcher, you might see that we haven't defined the variables we are filling yet. Let's set them up at the top as global variables. That should do it for our plumbing so let's go ahead and add a create contract function.

  41. Create Contract Function And to do so we can do almost what we did before when creating contracts from another contract, but instead of using the app method we will create a new contract based on what we already have. We want to use the new method of the FoodSafe contract. The FoodSafe contract that we created earlier has by default a new method on it. What this method will do is to actually upload the contract to the blockchain. The first parameter is additional parameters, but we don't need that for now so we just send in an empty string. The next is the transaction parameters. First we want to tell them which account we're going to send this from and we will be using our default account. The next parameter is the data that we're going to send and that will be the actual byte code for our contract. Now the last parameter that we need to set is to estimate for the gas. We could also set the gas price here if we wanted. If you're unsure of what to set here, you could use the gas used from when testing the contract in TestRPC as a guideline. Right now we're just going to set a very high number to ensure that we get it mined. That should be more than enough. Then we want to send in the callback function. And again, the first parameter is a variable for error and the second one is the actual deployed contract. First you want to ensure that the deployed contract actually has an address. And if it has an address we're going to set an actual object in the user interface. We haven't created this object yet, but we will quite soon. And the user interface object will actually be a textbox and we will call it contract address. We will set the value of it to the address of the deployed contract. That should be all we need for our create contract function. So now let's head over to the html interface by opening up the index.html file. As you see, this is a traditional html file. Since this is a blockchain course and not a design course, I'm going to keep the design of this application as simple as possible, but we can at least add a heading to our application. This will not win any awards for being the most beautiful application on the market, but it will serve its purpose. Next, let's add the placeholder for the address of the contract. And we want it to be a text input and we must remember to set the correct ID now and let's just add a placeholder text for it. That should do it. So the next thing that we need to do is to add a button to call the create contract method. I'll just add a couple of breaks here so that it looks a little bit better. And we want to set the on-click parameter to the name of our application function. And as part of the visual for the button, we enter create new contract. Make sure that everything is saved. Now it's time to give this a test so we'll fire up the development server by using the npm run dev command. And since this is JavaScript and HTML we really don't need to recompile before running this. Okay, so let's just copy the address to our application and open it up in a browser. It looks fantastic, doesn't it? So before we do anything else, we need to point MetaMask to our private Ethereum that we created earlier. To find the address for it we go into Azure and copy it. What we are looking for is the RPC endpoint. And point it to the right server. Great, and we'll fill up our account with some Ether. First we'll just copy the account and we go into the admin side. There we go. We want to bootstrap our account. We'll just keep it at 1000 Ether for now. Okay, when we're ready, let's expand the window. Click on create new contract. This again opens up the MetaMask in notification and we see that this has a quite high transaction cost. Of course, this will not be the real thing. It's because we set a very, very high gas limit. We'll go ahead and accept it. We wait for our contract to be mined. What do you know? It works! As you see, we got the deployed contract address back. If you hit the button again, a new contract will be deployed. The actual address could be printed on the product batch and be scanned directly into the application. The process of printing and scanning these codes will not be part of this project, but there are many technologies out there that will let you do so easily. This means that so far in this project we have created a contract for our application, we have set up the correct plumbing, installed the Solidity compiler, and compiled our own contract as well as being able to upload it to the blockchain from a very simple user interface. I'm very sure that you'll find this process useful when you start to develop your own blockchain applications.

  42. Demo: Load Existing and Read Information In this next demo we will build upon what we have done so far and load an existing contract. We will use the compiled uploaded contract to add to the trail and also get the location back from the contract. We have no time to waste so let's get back to Visual Studio Code. So now let's add a function called add new location. This will let us add the next location using the add new location function on the already existing contract. Let's load the address from the UI into a variable. Next we can use the contract that we compiled earlier in order to load the deployed contract into a variable. We do that by using the at function. Then we need to get that location ID, location name, and location secret from the user interface. So let's get the values from the UI that we need in order to create a new location and as we did last time we will make the calls to the UI now and create the elements later. First we want to get the location ID. Then the location name. The location secret. And the passphrase that we will use to encrypt and decrypt our secrets to encrypt and decrypt our secrets. We will use a library called CryptoJS and the only thing we need to do in order to use it is to add an import at the top of our code. The reason we can use CryptoJS like this is that it's already a dependency that has been added by the Truffle Webpack. So now we can go ahead and encrypt our secret and we will use the AES encryption. We'll pass the location secret and the passphrase and in order to get this as a storable string, we'll use the toString method. Now we should have everything we need and we can go ahead and make the call to the add new location function. We'll pass in the location ID, the location name, and the encrypted secret. And as always, we create a callback function and we can just go ahead and log it if there are any errors. Now remember to save and the next step is now to add the UI elements to the index.html file. We will copy this and make some input boxes for location ID, location name, secret, and passphrase. And we'll add a button for creating our new location. Okay, and at the same time let's also add a get button for getting the current location. Okay, then we go back to the app.js file and we're we're going to add the get current function there as well. To make it easy for ourselves now we'll just copy the code forgetting the contract from the address. As an early extreme programming adopter I would really like to refactor the code, but to keep it quick now, let's just do it like this. But please don't tell anyone I told you to do this. And to decrypt the message we also need the passphrase. Okay, we are ready to make the call. The first we need to know is the trail count so let's make a call to the get trail count. Now that we have the trail count so that we know where we are, we can make a call to the get location. And since this is 0 bound, we need to use trail count -1. Then we can start to fill in the user interface with the values that we have gotten. It is important that you remember the order of the return values. Now we want to get the encrypted secrets so that we can go ahead and decrypt it. To decrypt the secret we can go ahead and use the CryptoJS library again. And we must use the passphrase and we use the toString method to convert it to Utf8 characters. Then we can push the decrypted secret back to the user interface. Okay, let's save and head over to our browser again. Okay, so let's add a new contract, okay? Let's just copy the address. We can enter an ID, location name, and let's make a secret and a secret passphrase and we click on the add new location button. There we go again. We are asked to pay for this and we click on accept and we need to wait for this to be mined, but when it has, we can refresh and we paste in the address of our created contract, click the get current location, and as we see, we don't get the secret yet because we haven't entered a passphrase. So let's do so, and click again. And that's it. We have created our own blockchain application. It's very simple, but also very effective. We are able to create and upload a contract. We are setting values for it. We are making things secret for everyone that doesn't know the passphrase and we are able to add it to the blockchain and get it back.

  43. Summary In this module we have built a small sample application called FoodSafe. It compiles and uploads a contract for each product batch. It lets you add to the trail of locations with the storing of secrets along the way. And lastly, we were able to retrieve the information from the blockchain.

  44. Summary and Way Forward Learning Goals Review Summary and way forward. Let's have a brief look at the learning goals we set in the beginning of the course. We started by looking at the basics of blockchain technology and you should now understand the most important aspects of the underlying technology. For the general developer this is really the level you would need to be at in order to do day-to-day development on any blockchain implementation. We have spent quite a bit of the course looking to Ethereum. This is currently the premium development platform for developing blockchain applications. If you understand Ethereum you are very likely to be able to develop for other blockchains as well. By using Solidity we have created both simple and more complex contracts and again, this is knowledge that you should be able to easily transfer to other implementations of blockchain if you wish. No fundamentals course would be complete without making an actual application and together we made a very simple but effective application for tracking produced food in a secure and tamper-free way. We also enabled the application to share secrets on a publicly available blockchain. It has been said that about 80% of the current applications using blockchain would be better if done traditionally. I tend to agree with that. Currently there are a lot of people looking for a problem to solve with the technology rather than starting with a problem itself. I hope the focus will shift more towards seeing and solving the problems that can actually only be solved with this technology rather than trying to reinvent the wheel for existing applications. And in order to do so, you must understand the limitations of blockchain. Smart contracts isn't for storing large amounts of data or advanced application logic. You should keep as much as possible out of the blockchain and keep the code and contracts as simple and effective as possible. We are only seeing the start of the blockchain revolution. The next generation of tools and even blockchain implementations themselves will be different from what we have now. But with what you have learned in this course, you are well equipped to get started today as well as following the road ahead. Don't make the mistake of thinking of the blockchain as a database, but you should also not make the mistake of thinking that the blockchain can be maintained as a database. You have no tools for management or updating the chain. You cannot do joints and queries like you are used to and in order to be successful at developing for the blockchain, you must think about how you will maintain and support your application before rolling it out. Undoing or redoing your work is more or less not an option. With this course you have gotten off to a good start. It is important that you continue to learn and that you don't think that the blockchains of today is how they will look in 5 or 10 years. My best advice to you here is to continuously search Pluralsight for new courses on the implementations of blockchain and DAPP development. Another way to continue to learn is to use online forums and you should also remember to use the discussion forum at Pluralsight for this course. I can promise that I'll answer questions there on a regular basis, but if you struggle with something, it is usually a very good place to get help from your peers.

  45. Way Forward So what does the future hold? Well, it's hard to predict things, especially the future, but if we look at the current and historic trends, a few areas seem to be quite certain. First of all, the blockchain concept of proof of work will have to change. It's not sustainable to burn this much energy on mining what is really something that doesn't give any real value. The most likely outcome is the transition to proof of stake where you put money directly into the chain without wasting energy in the process. Ethereum Enterprise Alliance seems to be growing rapidly with new companies piling on every quarter. This is good news with more enterprise acceptance and support, more applications and investments will come. It also seems like banking and payment is changing. Major banks have already created their own crypto currency for inter-bank transactions to avoid transaction and currency costs. The last area I would like to bring up is that the blockchain development will up the focus on distributed application design with or without the underlying technology of blockchain. The way the modern application architecture is today is very different from how it was only five years ago. Well, to do a real short recap of this course, we started with an overview of the modules before we went into the general blockchain concepts. We spent quite a bit on Ethereum and beginning of DAPPS development. To make sure that you were able to be an effective developer right away, I showed you in detail how to set up the development environment. Smart contracts is the base of development for blockchain and I showed you how you can make use of everything you have learned in the sample application that we created. Lastly, I hope that I've given you some good advice on the way, as well as some prediction of the future that will stand the test of time. With that, I want to thank you for watching this course. It has been a real pleasure to make and I really hope that you will take this knowledge and create something fantastic that you share with the world.