Building a Cryptocurrency with Kotlin : Part 1

File:Kotlin-logo.svgKotlin has been becoming more and more mature with every release. We arguably have the most concise modern programming language that currently exists. With language idioms like data classes, extensions, kotlin objects, delegated properties, lambdas and of course, the latest version of Kotlin adds coroutine support. Lets talk about Node.js for a second. Node.js helped us to create many amazing websites and services, and provides numerous modules to make our lives as developers easier. But just because a tool is good enough does not mean we should stop innovation there. Kotlin is now Node.js' competitor because Kotlin's powerful language idioms enable us to create a powerful and fast framework for building asynchronous servers and clients, called Ktor.


Related imageLets go back in time for a moment. Back in 2008 a small C++ side project was started by Satoshi Nakamoto. This project would change the world for ever. 10 years later Bitcoin managed to inspire dozens of crypto currency projects, in languages such as Rust and even Java. With features ranging from proof-of-stake, smart contracts and atomic-swaps.

For this series of tutorials we will learn how cryptocurrencies are written by creating our own, by using Kotlin and nothing else. This currency will have most common features like a blockchain, peer-to-peer consensus, transaction validation, proof-of-work, wallets, smart contracts, and more. Don't worry its actually easier than you think. Also for simplicity we will skip some security features, so final result will not be fit for production use. The reason for these tutorial series is to learn about Kotlin and cryptocurrencies by writing one from scratch. So lets get started!

It All Starts With a Chain of Blocks

Blockchain is a very simple data structure, similar to a linked list. The main difference is that each block holds the hash of the previous block. Think of a hash as a unique signature of that block, given all the data it currently contains, and even if a single bit of that data is different the hash would change. Just like a linked list, each item in the block chain has data. The base minimum data that a block needs to hold are:
  • index: the number of the block in the chain.
  • previous hash: calculated hash of the previous block at the moment of creation of the current block.
  • data: this could be any data like transaction inputs and outputs, smart contract states and inputs, or any other data you wish to store. For this lesson we will keep a string value but in the next lessons we will store transaction data in this field.
  • hash: unlike other fields this is a function that is called on the block to calculate its hash.

There is a built in security feature in such a data structure. In order for a malicious actor to change a single block's data, the actor would have to modify the hash of that block and all the block following it in order to maintain the validity of the data structure.

We will create a class to help us manage our collection of Blocks. Because we only need a single instance of the BlockChain we will make it a Kotlin singleton. For this lesson we will keep the BlockChain object simple. It will have two main functions addNewBlock and isValid. Lets see how our singleton object would look like in Kotlin.

To add a new block to our list of blocks we simply create a new instance on the Block data class with the index of the current block, the hash of the previous block, the time stamp and the data string.

To validate the chain we will iterate through every Block until the genesis block and make sure the previousHash matches the actual hash of the block, and the first block matches the hardcoded genesis block, that way we know none of the individual block has been modified. In the next lesson we will see how to pick the longest chain in the network to meet consensus but for now lets see how to implements the validation function:

And to add some final touches to our node implementation lets create couple endpoints to call the functions on or BlockChain object. But first lets add the following Ktor dependencies to our gradle build file:
    compile "io.ktor:ktor-server-netty:$ktor_version"
    compile "io.ktor:ktor-html-builder:$ktor_version"

Next we will implement a simple Ktor Application module and create 3 endpoints, root that will display a list of all blocks, /add that will generate a new block on our chain, and finally a /isValid endpoint to check the validity of the current chain.


And as you can see the basic underlying structure of most blockchains is very simple. Hopefully this lesson helped you understand the basics of blockchain, the fundamental technology of most crypto currencies.


Comments

  1. I am all that much satisfied with the substance you have specified. I needed to thank you for this awesome article.  Coins Libra

    ReplyDelete
  2. You may find that cryptocurrency is for you or you may not but rather at any rate you'll have the option to talk with a level of sureness and learning that others won't have.
    TradingPlatform

    ReplyDelete
  3. Yes i am totally agreed with this article and i just want say that this article is very nice and very informative article.I will make sure to be reading your blog more. You made a good point but I can't help but wonder, what about the other side? !!!!!!Thanks Payeer Invest

    ReplyDelete
  4. Thanks for sharing is so amazing and helpful to us.
    Buy Hydrocodone online

    ReplyDelete
  5. Looking for English to Spanish Translators? We provide professional Translation Services at highly competitive rates without compromising the quality.
    english to spanish translation services

    ReplyDelete
  6. Thanks a lot for sharing
    Having good health is what most people out there wants but can not achieve. some people takes buy ibogaine online AND buy weed online to get it.

    ReplyDelete
  7. Most of the Calgary roofers are going to be certified, dependable, and honest in their work. But not all roofing companies in Calgary offer the same quality of shingles or other roofing materials. And every Calgary roofing company has different guarantees and warranty offers.

    ReplyDelete
  8. medical care is what many people lack in the interior areas of the world. people face a lot of health issues everyday without solution. buy magic mushroom, Buy weed online, Buy heroin online

    ReplyDelete
  9. Mr Sanjay Baghela focus to reflects as the best leader of SEO in the world, and his dedication and expertise in SEO field make him enable as the owner of the best  BEST SEO Expert India. You can connect with him anytime and you can see his knowledge about SEO itself. Drop your request and dial his number now! best seo expert in india

    ReplyDelete
  10. With Sanjay Baghela, your business Website is in safe hands. He and his team are the best SEO Expert in India the leading digital marketing field.
    Best SEO Expert In India
    Best Seo Company in India

    ReplyDelete
  11. Thanks for sharing the post.. parents are worlds best person in each lives of individual..they need or must succeed to sustain needs of the family. Best bitcoin trading software

    ReplyDelete
  12. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info. ethereum generator online 2020

    ReplyDelete
  13. Some truly wonderful work on behalf of the owner of this internet site , perfectly great articles . comprar bitcoin brasil

    ReplyDelete
  14. What could be one big problem with this system of transaction? No members can sell Bitcoin if they don't have one. It means you have to first acquire it by tendering something valuable you possess or through Bitcoin mining. A large chunk of these valuable things ultimately goes to a person who is the original seller of Bitcoin. Of course, some amount as profit will certainly go to other members who are not the original producer of Bitcoins. Some members will also lose their valuables. As demand for Bitcoin increases, the original seller can produce more Bitcoins as is being done by central banks. As the price of Bitcoin increases in their market, the original producers can slowly release their bitcoins into the system and make a huge profit..   Visit here today

    ReplyDelete
  15. I learn some new stuff from it too, thanks for sharing your information. url

    ReplyDelete
  16. I have read all the comments and suggestions posted by the visitors for this article are very fine,We will wait for your next article so only.Thanks! btc to skrill

    ReplyDelete
  17. It's very useful article with inforamtive and insightful content and i had good experience with this information. We, at the CRS info solutions ,help candidates in acquiring certificates, master interview questions, and prepare brilliant resumes.Go through some helpful and rich content Salesforce Admin syllabus from learn in real time team. This Salesforce Development syllabus is 100% practical and highly worth reading. Recently i have gone through Salesforce Development syllabus and Salesforce Admin syllabus which includes Salesforce training in USA so practically designed.

    ReplyDelete
  18. In the event that a fiat cash, similar to the USD or GBP, gets swelled, its value rises and its buying power drops.Getnode Test

    ReplyDelete
  19. This is my first time visit to your blog and I am very interested in the articles that you serve. Provide enough knowledge for me. Thank you for sharing useful and don't forget, keep sharing useful info: Bitmain antminer S19 Pro price

    ReplyDelete
  20. Amazing post with quality information! Many wonder, how to recover stolen or scammed Bitcoin? Hire a bitcoin recovery expert online

    ReplyDelete
  21. Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info. recesión económica

    ReplyDelete
  22. I was surfing the Internet for information and came across your blog. I am impressed by the information you have on this blog. It shows how well you understand this subject. recesión

    ReplyDelete
  23. It was wondering if I could use this write-up on my other website, I will link it back to your website though.Great Thanks. 도메인 가격

    ReplyDelete
  24. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article. 도메인 등록 절차

    ReplyDelete
  25. The post is written in very a good manner and it contains many useful information for me. 借錢管道

    ReplyDelete
  26. very interesting post.this is my first time visit here.i found so mmany interesting stuff in your blog especially its discussion..thanks for the post! 小額借錢

    ReplyDelete
  27. It's very useful blog post with informative and insightful content and i had good experience with this information.I have gone through CRS Info Solutions Home which really nice.Find this real time DevOps Training and great teaching. Join now on Selenium Training online course. Upskill career with Tableau training by crs info solutions. Latest trending course is Salesforce Lightning training with excellent jobs.

    ReplyDelete
  28. Bitcoin is an open-source item, available by any individual who is a client. BTC escrow

    ReplyDelete
  29. There will be an area with a box for you to paste a code when you want to send money to someone or to yourself on an exchange or different wallet. accept bitcoin

    ReplyDelete
  30. Amazing post with quality information! Many wonder, how to recover stolen or scammed Bitcoin? bandarqq terpercaya

    ReplyDelete
  31. Forex is my passion, that's why I sincerely love supporting all and sundry to conquer their demanding situations and come to be worthwhile in their very own buying and selling.How to trade forex and cryptocurrency

    ReplyDelete
  32. Very efficiently written information. It will be beneficial to anybody who utilizes it, including me. Keep up the good work. For sure i will check out more posts. This site seems to get a good amount of visitors. how to track and recover stolen bitcoin

    ReplyDelete
  33. A famous enterprise to acquire the most cutting-edge charge in Bitcoin valuation is XE.How to recover your stolen bitcoin

    ReplyDelete

Post a comment

Popular posts from this blog

Android Architecture Components : LiveData

Android Data Binding : Dynamic RecyclerView Adapter