Creating a blockchain with Javascript (Blockchain, part 1)
- January 7, 2024
- Posted by: MainInstructor
- Category: C Go JavaScript Node
Video Title: Creating a blockchain with Javascript (Blockchain, part 1)
Hi everyone my name is Kavya and in this video we’re going to write a very tiny blockchain in JavaScript now it won’t be anything too fancy but it will be just enough so you can understand how a blockchain actually works we’ll call this blockchain sabzi coin and let’s get
Started okay so here I’ve opened up an empty directory in Visual Studio code and let’s start by creating a new JavaScript file to store all of our code I’m going to call this main Jas and I’m going to start by defining what a block on our blockchain will look like so I’m
Going to create a class called block and I’m going to give it a constructor and this constructor will receive the properties of this block and so each block will have an index a timestamp some data and the previous hatch I’m going to set this by default to empty now these are pretty self-explanatory
The index is option I’m going to tell us where the block sits on the chain the timestamp will tell us when the block was created and then we have data and this might include any type of data that you want to associate with this block now in case of recurrency you might want
To store the details of the transaction in here such as how much money was transferred and who was the sender and the receiver and then the previous hash is a string that contains the hash of the block before this one now this is very important and it ensures the
Integrity of our blockchain so I’m going to keep track of all these values so I’m going to say this dot index equals index this dot timestamp equals timestamp this dot data equals theta this dot previous to hash equals previous hash all right and now I’m also going to add another
Property to our class and that’s going to be the hash property now this will contain the hash of our block so we need a way to calculate it so I’m going to set an empty for now going to create a new method and I’m going to call this one calculate cash
And all that this function is going to do is calculate the hash function of this block so it’s going to take the properties of this block run them through them hash function and then return the hash this will identify our block on the blockchain now I’m going to
Use sha-256 as a hash function but this is not available in JavaScript by default so I actually need to import a library they can do this so I’m going to open up a terminal and I’m going to install crypto j/s I’m going to do that through NPM so I’m going to run NPM
Installed – save crypto – Jas and this will download the library and we’ll put them in into the node modules directory so we will have crypto jazz and we and here we have all the hash functions that it supports so I’m going to close up my terminal and now I can import the
Sha-256 function so I’m going to take constant sha-256 equals require crypto j s / sha-256 all right there we go so now we have imported the library and we can start using it so this function right here calculate hash it should return a sha-256 hash of our index plus our
Previous hash plus the timestamp of our block plus and then I’m going to stringify the data object the data object so I’m going to stringify this JSON and I’m going to take the output of shell 256 and I’m going to cast it to a strength because otherwise we get an
Object that this library returns so now I can use the task function so I’m going to say that the hash equals this dot calculate hash and so when we create our block we pass along these parameters and it will calculate the hash of our block so that was our block class let’s now
Create a new class for our block chain so class blockchain I will give it a constructor as well and the constructor is responsible for initializing our blockchain so I’m going to create a property chain inside this class and that is going to be an array of blocks
Now the first block on a blockchain is called a Genesis block and this should be added manually so I’m going to create a method to do this so I’m going to call this method create Genesis block and this is going to return a new block so
I’m going to say return new block and this is going to be of index 0 we’re going to give it a date this can be anything you want let’s pick first of January if this year we’re going to give it some data I’m just going to give it a string that says
Genesis block and then the previous hash which is you know it kind of doesn’t exist this block is the first block so it cannot point to any previous blocks so this can be any random data I’m just going to set it to 0 okay and then back in our constructor we’re going to
Initialize our chain not as an empty array but as an array which contains our Genesis block all right now I’m also going to add some other methods that could be useful in the future so I’m going to add a get latest block method and I’m also going to add an add block
Method that will receive in block now the get latest block method is really simple it returns the latest Block in the chain so we’re going to return this chain and we’re going to return the last element that’s length minus 1 there we go ok so let’s now implement our add
Block method and this method is responsible for adding a new block on to the chain but it needs to do some work before it just pushes it on to the error the first thing that it needs to do is it needs to set the previous hash
Property of the new block and it is to set this to the last block on our chain so we’re going to get the latest block and then we’re going to get the hash of that madest block the next thing that we need to do is now that we’ve changed our
Block is that we to recalculate its hash so every time we change any of these properties in our block the hash function should be changed as well so I’m going to say new blog hash equals new blog dot calculate hash all right that should update it and
Now I’m ready to push it onto the chain so I’m going to say this dot chain dot push the new block and there we go now in reality you can’t add a new block so easily because there are numerous checks in place but for our little block chain
It’s more than enough and it demonstrates how a block chain actually works so let’s now test it to test it I’m going to create a instance of my block chain so I’m going to create a variable Saticoy and I’m going to say it’s a new block chain there we go and
I’m also going to add a few blocks so I’m going to say so edgy coin dot add block and then I’m going to create a new block and this is going to be block with the next one post it on the 10th 2017 and add data object I’m just going to
Pass amount equals 4 for example and then I’m going to copy paste this line I’m going to add another block this block will have it next to its posted to this later transfers maybe 10 coins whatever this data can be anything that you want okay so let’s now see what our block chain
Looks like so I’m going to console lock our block chain I’m going to stringify before we output it to the screen so it’s nice and readable so I’m going to string a 5 savage equine and I’m going to use 4 spaces to format it I’m going
To say the file I’m going to open up the terminal and now I’m going to run our main file and there we go this is what our block chain looks like right now so our block chain is this object right here it contains a property chain which
Is an array and this area contains all of the blocks on our chain and you can see that each block references the previous block so let’s take the latest one for example this block references the previous blocks were here we see that the previous hash is C 37
And if we go to the previous block this block has C 37 as a hash great so now that we know that that works let’s try and do something different block chains are great because once a block is added it cannot be changed without invalidating the rest of the chain but
In this implementation there is no way for me to verify the integrity of our block chain so let’s add a new method to our block chain in the closer terminal here and I’m going to call this method is chain Fallot and this is going to return either true if the chain is valid
And false if something is wrong now in order to verify the integrity we’re going to loop over our entire chain so I’m going to say for I equals 1 we’re not going to start with block 0 because block 0 is a Genesis block we’re going
To start with index 1 so we’re going to set I to 1 we’re going to loop until the end of the chain so until the length of the chain and we’re going to increase I by 1 every time and then we’re going to grab the current block and the previous
Block so I’m going to say that the current block equals this chain I so I’m going to take the I position in the chain and then I’m also going to say that the previous block is the same but I minus 1 so we’re going one block back
And now we can actually check if these blocks are properly linked together now the first thing that we’re going to test is if the hash of the block is still valid so I’m going to check if the current block the hash of the current block is not equal to current block
Calculate hash so here we’re going to ask it to recalculate the hash well if it’s not equal then our chain is just invalid and something is wrong the actual hash of a block doesn’t match up with what it’s property set now the next check that we need to do is we need to
Check if our block points to a correct previous block so we need to check in the previous hash property is correctly set so I’m going to check if our current blog has a previous hash that is not equal to the hash of our previous block and if that’s the case
Then again we know that something is wrong because our current block does not point to the previous block it points to something else that might not exist now if it boots through all of our blocks and it hasn’t returned false then we obviously have to return true because
Then our chain is perfectly valid so that’s it for the verified function now we can actually verify the integrity of our block chain so let’s do that right now I’m going to scroll down so I’m going to leave these two two lines in and I’m just going to check if our block
Chain is valid so I’m going to comment oops so I’m going to comment this line out and I’m just going to say console.log is block chain valid question mark and then we’re going to add sanity coin dot is chain fala so let’s run that right now and it says yes
Our block chain is valid and that’s because we haven’t done anything to tamper with our block chain now let’s try and tamper with our block chain so I’m going to leave this line in again and now I’m going to try and change block two so I’m going to say that
Sanji coin dot chain I’m going to take the first block here and I’m going to override its data I’m going to say that instead of transferring you know just four coins I’m going to say that we transferred 100 points I want to make myself rich here so after I’ve done that
I’m going to copy and paste this line here and I’m going to recheck if our blockchain is valid so I’m going to run this again and you can see the first time our blockchain is valid and then we tamper with one of the blocks and then
All of a sudden says hey you know something is not right here this is not valid anymore okay well you might think there is another way I can tamper with this here I’ve changed the data of the block but I didn’t recomputation I say well I’m going to be clever here and I’m
Going to take that same Blagh here and I’m going to recalculate attach so I’m going to say sabzi coin not chain one done calculate hash ok so right now if I do this I can port with the block ivory calculated it’s hash and so that move on work well let’s run it
Again and sure enough no it doesn’t work because right now we’ve tampered with one of the blocks but the relationship with its previous block is now been broken so again the blockchain is meant to add blocks to it but to never delete a block or to never change a block again
Now of course if you detect that a new block broke your chain or if something is wrong with your chain then you should have a mechanism that rolls back the changes and then puts your block chain back in a correct state but that is beyond the scope of this video it also
Lacks many features such as proof of work or appear to be network to communicate with other miners and it even doesn’t check if you had enough funds to make a transaction so there are lots of limitations to my little blockchain right here but it perfectly demonstrates how a blockchain works
Behind the scenes so that was it for this video I hope you liked it and if you did leave a thumbs up on this video or subscribe to my channel thank you very much for watching and I’ll see you in the next video
-
Sale!
Wireless WIFI Repeater Extender Amplifier Booster 300Mbps
$29.99$14.99 Add to cartWireless WIFI Repeater Extender Amplifier Booster 300Mbps
Categories: Electronics, Wi-Fi Router, Wireless Wi-Fi Extender Tags: 300Mbps, 802.11N, Amplifier, Booster, Extender, mobile wi-fi booster, Remote, WIFI, Wireless, Wireless WIFI, Wireless WIFI Repeater, Wireless WIFI Repeater Extender, Wireless WIFI Repeater Extender Amplifier, Wireless WIFI Repeater Extender Amplifier Booster, Wireless WIFI Repeater Extender Amplifier Booster 300Mbps$29.99$14.99 -
Sale!
Full RGB Light Design Gaming Headset Headphones with Mic
$24.99$14.99 Add to cartFull RGB Light Design Gaming Headset Headphones with Mic
Categories: Electronics, Gaming, Gaming Headsets Tags: Design, Full, Full RGB Light Design Gaming Headset, Full RGB Light Design Gaming Headset Headphones, Full RGB Light Design Gaming Headset Headphones with Mic, Gamer, Gaming, Gaming Headset Headphones, gaming headset wireless, Headphone, Headphones, Headset, Light, Mic, Package, RGB$24.99$14.99 -
Sale!
Wireless BlueTooth Multi-Device Keyboard Mouse Combo
$39.99$19.99 Add to cartWireless BlueTooth Multi-Device Keyboard Mouse Combo
Categories: Electronics, Gaming, Gaming Keyboards, Keyboard Mouse Combos Tags: Combo, Keyboard, keyboard mouse combos, Mouse, MultiDevice, Set, WireKeyboard Mouse Combo, Wireless, Wireless BlueTooth Keyboard Mouse Combo, Wireless BlueTooth Keyboard Mouse Combos, Wireless BlueTooth Multi-Device Keyboard Mouse Combo, Wireless BlueTooth Multi-Device Keyboard Mouse Combos$39.99$19.99 -
Sale!
High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
$199.99$139.99 Add to cartHigh Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar
Categories: Gaming, Gaming Chairs Tags: Adjustable, Chair, computer chairs, Desk, Executive, Gaming, Girl, Headrest, High, High Back Leather Executive Adjustable Swivel Gaming Chair, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest, High Back Leather Executive Adjustable Swivel Gaming Chair with Headrest and Lumbar, High Back Leather Executive Adjustable Swivel Gaming Chairs, Leather, Lumbar, Office, Racing, Swivel$199.99$139.99 -
Sale!
Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
$29.99$19.99 Select optionsProfessional LED Light Wired Gaming Headphones with Noise Cancelling Microphone
SKU: N/A Categories: Electronics, Gaming, Gaming Headsets Tags: Cancelling, Gaming, Gaming Headphones with Noise Cancelling Microphone, gaming headset, Headphones, Headset, LED, Light, Mic, Microphone, Noise, Professional, Professional LED Light Wired Gaming Headphones, Professional LED Light Wired Gaming Headphones with Noise Cancelling Microphone, Wired, Wired Gaming Headphones, Wired Gaming Headphones with Noise Cancelling Microphone$29.99$19.99 -
Sale!
Gaming Desk with LED Lights USB Power Outlets and Charging Ports
$349.99$249.99 Select optionsGaming Desk with LED Lights USB Power Outlets and Charging Ports
SKU: N/A Categories: Computer Desk, Gaming, Gaming Desk Tags: and Charging Ports, Charging, Desk, Desks, Gaming, gaming desk with led lights, Gaming Desks with LED Lights, Home, LED, Lights, Monitor, Office, Outlets, Port, Power, Room, Stand, USB, USB Power Outlets, White, Workstation$349.99$249.99 -
Sale!
Wired Mixed Backlit Anti-Ghosting Gaming Keyboard
$99.99$79.99 Add to cartWired Mixed Backlit Anti-Ghosting Gaming Keyboard
Categories: Electronics, Gaming, Gaming Keyboards Tags: Antighosting, Backlit, Blue, brown, Gaming, Gaming Keyboard, gaming keyboards, gaming keyboards and mouse, Keyboard, Laptop, Switch, Wired, Wired Mixed Backlit Anti-Ghosting Gaming Keyboard, Wired Mixed Backlit Anti-Ghosting Gaming Keyboards, Wired Mixed Backlit Gaming Keyboard$99.99$79.99 -
Sale!
Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
$119.99$59.99 Add to cartWireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset
Categories: Electronics, Gaming, Gaming Headsets Tags: 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, ANC, Audio, Bluetooth, Cancellation, Ear, Earphone, gaming headset, Headphones, Headset, Hi-Res Over the Ear Headphones Headset, HiRes, Noise, Wireless, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Headphones, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headset, Wireless Bluetooth 5.3 ANC Noise Cancellation Hi-Res Over the Ear Headphones Headsets$119.99$59.99 -
Sale!
Wired Sports Gaming Headset Earbuds with Microphone
$19.99$9.99 Select optionsWired Sports Gaming Headset Earbuds with Microphone
SKU: N/A Categories: Gaming, Gaming Headsets Tags: Accessories, Earbud, Earphone, Earphones, Gaming, gaming headset with microphone, Headphones, Headset, IOS, Microphone, Sports, Wired, Wired Sports Gaming Headset Earbuds, Wired Sports Gaming Headset Earbuds with Microphone, Wired Sports Headset Earbuds$19.99$9.99 -
Sale!
150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
$49.99$29.99 Add to cart150W Universal Multi USB Fast Charger 16 Port MAX Charging Station
Categories: Charging Stations, Electronics Tags: 150W, 150W Charging Station, 150W Universal Multi USB Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Station, 150W Universal Multi USB Fast Charger 16 Port MAX Charging Stations, 150W Universal Multi USB MAX Charging Station, 16 Port MAX Charging Station, 3.5A, Charger, Charging, Fast, laptop charging stations, Max, Multi, Port, Stand, Station, Universal, USB$49.99$29.99
TypeError: block.transactions is not iterable
at Blockchain.getBalanceOfAddress (C:Users34949node_modulessavjeecoinBlockchain.js:92:38)
at Object.<anonymous> (C:Users34949node_modulessavjeecoinBlockchain.js:137:59)
Great Video. Thanks for this informative short video
Thanks for the video, this is fun!!! 😄
Amazing explanation, I got it now!
Hello! junior programmer here. I got fascinated when I saw your video. I've tried to do all the steps shown in the video but still I couldn't manage to output my blocks. I tried everything and checked everything is correct or not. It says " TypeError: Cannot read properties of undefined (reading 'hash') " under the code " newBlock.previousHash = this.getLatestBlock().hash; ". I know it is an old video but maybe there are still viewers that want to help me out. thank you
Easy explained and good to follow. Thanks!
is blockchain technology built on top of linklist 😉
Excelente
From this precious example one must first get the concept of data structures and algorithms to understand block chain efficiently.
What a great video, and what a great teaching methodology, I really appreciate your contribution to enhancing the programming skills in Blockchain. I have a question, according to my research. I want to check the block propagation latency through plotting. Is it possible to do so? if yes, how can I modify the code?
Great! I was learning blockchain but with a traditional school teaching for weeks and I didn’t understand nothing but with your videos I completely hooked up great and very simple way to learn thanks and appreciate to share your knowledge ❤
Good job! The only thing, I think timestamp should be represented as 1483218000000 instead of "01/01/2017".
White theme 🤯
Thank you 🙏
Wow! This explanation demystified the whole concept of blockchain . Thanks 😊👍
hey im doing this on sublime text and how and how do import this crypto js file from
What if data was a picture or a document? Thank you
How do you get hash at first hm
Man please i need to know what visual studio theme is that one pls kKKK thx a lot for the content 🙂 very clear explanation :3
ReferenceError: getLatestBlock is not defined
at Object.<anonymous> (C:Usersfatoosavjeecoinmain.js:26:1)
at Module._compile (node:internal/modules/cjs/loader:1120:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1174:10)
at Module.load (node:internal/modules/cjs/loader:998:32)
at Module._load (node:internal/modules/cjs/loader:839:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
please help thats what is shows when i run main.js