Code your own blockchain in less than 200 lines of Go!

  • Create your own blockchain
  • Understand how hashing works in maintaining integrity of the blockchain
  • See how new blocks get added
  • See how tiebreakers get resolved when multiple nodes generate blocks
  • View your blockchain in a web browser
  • Write new blocks
  • Get a foundational understanding of the blockchain so you can decide where your journey takes you from here!

Let’s get started!

  • Index is the position of the data record in the blockchain
  • Timestamp is automatically determined and is the time the data is written
  • BPM or beats per minute, is your pulse rate
  • Hash is a SHA256 identifier representing this data record
  • PrevHash is the SHA256 identifier of the previous record in the chain
  • To save space. Hashes are derived from all the data that is on the block. In our case, we only have a few data points but imagine we have data from hundreds, thousands or millions of previous blocks. It’s much more efficient to hash that data into a single SHA256 string or hash the hashes than to copy all the data in preceding blocks over and over again.
  • Preserve integrity of the blockchain. By storing previous hashes like we do in the diagram above, we’re able to ensure the blocks in the blockchain are in the right order. If a malicious party were to come in and try to manipulate the data (for example, to change our heart rate to fix life insurance prices), the hashes would change quickly and the chain would “break”, and everyone would know to not trust that malicious chain.
  • spew.Dump is a convenient function that pretty prints our structs into the console. It’s useful for debugging.
  • for testing POST requests, we like to use Postman. curl works well too, if you just can’t get away from the terminal.
  • godotenv.Load() allows us to read in variables like our port number from the.env file we placed at the root of our directory so we don’t have to hardcode them (gross!) throughout our app.
  • genesisBlock is the most important part of the main function. We need to supply our blockchain with an initial block, or else a new block will not be able to compare its previous hash to anything, since a previous hash doesn’t exist.
  • We isolate the genesis block into its own go routine so we can have a separation of concerns from our blockchain logic and our web server logic. This will work without the go routine but it’s just cleaner this way.

Tada! We’re done!

By popular demand we’ve added follow-ups to this tutorial! Check them out!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Coral Health

Coral Health

2.7K Followers

Take control of your health. Consolidate records, track medications, set reminders, and monitor health trends with the free #CoralHealthApp.