DEV Community

Cover image for Creating a blockchain in 60 lines of Javascript

Creating a blockchain in 60 lines of Javascript

FreakCdev on October 29, 2021

In recent years, cryptocurrencies and blockchains are two uprising fields, so today, I will share my way of creating a blockchain in Javascript in ...
Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Thank you sincerely for writing a post titled like this that doesn't just: include a library, set some parameters, and call a function - those kind of posts are garbage.

Dev.to needs more posts like this - real content that is actually interesting. Please keep up the good work 👍

Collapse
 
alvarezgarcia profile image
Alvarez García

I think that maybe another post showing differences between var, let and const it' s the real deal.

...

Being serious, I wish we have more quality posts like this.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Like this one?

Collapse
 
wahidn profile image
WahidN

I totally agree! I hate those posts/tutorials that do nothing but use a package and doesnt explain anything

Collapse
 
freakcdev297 profile image
FreakCdev

Thanks a lot man!

Collapse
 
rineezlivares profile image
Rineez Ahmed

Please write about Proof of stake

Collapse
 
freakcdev297 profile image
FreakCdev

Sure! Follow me to get the notification of the next article!

Collapse
 
jaybit33 profile image
Justin Roseman

Smart contracts would be great

Collapse
 
labzdjee profile image
Gérard Gauthier

Very interesting. I was with you until your mentioning log16(difficulty): where do you use this log16 function? As a parameter in the mine function? Elsewhere?

Collapse
 
freakcdev297 profile image
FreakCdev

What I meant was log base 16 of the difficulty, it is a better since the "real difficulty" should not drop or increase by a huge margin, and Bitcoin also uses it.

You can create a simple log16 function like this:

function log16(n) {
    return Math.log(n) / Math.log(16);
}
Enter fullscreen mode Exit fullscreen mode

So the new mine method should look like this:

    mine(difficulty) {
        while (!this.hash.startsWith(Array(Math.round(log16(difficulty)) + 1).join("0"))) {
            this.nonce++;
            this.hash = this.getHash();
        }
    }
Enter fullscreen mode Exit fullscreen mode

Also, for a little bonus, Bitcoin also requires 8 zeros by default so if you want to make it Bitcoin-like, it should be "00000000"+Array(Math.round(log16(difficulty)) + 1).join("0").

Collapse
 
labzdjee profile image
Gérard Gauthier

Thank you! That's is very clear. Effectively not as a parameter in the mine function as I mistakenly mentioned it but included in the calculation itself. It looks like the proof of work starts quite harsh with 8 zeroes and evolves quite slowly because of log16. Except maybe if one more "0" adds a lot of more difficulty in the computational demand.

Collapse
 
tqbit profile image
tq-bit

I dare to say this post is one of the best I've read on dev.to.

I'd love to read more about proof-of-work and proof-of-stake, perhaps also the more upgraded variations you mention.

Collapse
 
tqbit profile image
tq-bit

PS: I'd like to add that I used your post and replicated its functionality in typescript. It's longer than 60 lines, but I would like to publish it to a Public Github Repos.

Would you grant me the permission to do so? I'd add a reference to your article and to your github repos as well.

Collapse
 
freakcdev297 profile image
FreakCdev

Of course you can! The code is 100% open-source and the whole point of this article is sharing knowledge!

Collapse
 
tawsbob profile image
Dellean Santos

I think the most complex is to make the consensus of the network, the way of mining (proof of work for example) the block acceptance rules and the entire ecosystem, the blockchain itself is just a "database".

Collapse
 
freakcdev297 profile image
FreakCdev

indeed!

Collapse
 
raymclee profile image
Collapse
 
freakcdev297 profile image
FreakCdev

Thanks for commenting this, I have learnt a lot of Simply Explained!

Collapse
 
tomavelev profile image
Toma • Edited

Good post for understanding the basics. The only thing left is some simple synchronisation with a network and the solution of the Byzantine Generals Problem offered by Satoshi.

Collapse
 
annajmcdougall profile image
Anna J McDougall

For me (with effectively zero blockchain knowledge but advanced JavaScript), I was with you until the 'nonce' and 'mine' part. I think I'll have to check out the YouTube you linked to get the full story there! Regardless, this did help clarify a few of the basics for me, so thank you!

Collapse
 
jacmkno profile image
jacmkno

"Catching up to others" after changing the chain is impossible without the need to compute "nonce" anyway, right? Since the hash always include the previous hash, that does ensure the order is preserved too, so what, is the point of "nonce", except just for supporting the mining dificulty? Is that it's only purpose?

Great work! thanks for taking the time to craft this pure-value post!

Collapse
 
freakcdev297 profile image
FreakCdev • Edited

In a peer to peer network: If you don't have the nonce value, you can change data and then change the hash to what getHash returns, same with prevHash. You can do that with all following blocks and still get a valid chain. You can do that with thousands of nodes and manipulate the chain. But with PoW, it's not dependent on the majority of nodes, it depends on the length of the chain. If you submit a faulty chain, and you don't have enough computational power, your chain will likely be shorter and shorter than the chain from normal miners as time progresses, so your chain will be invalid. And technically, because of rewards, people would like to contribute to the chain more than attacking it.

Please correct me if I'm wrong, I'm learning as I'm writing :D

Collapse
 
smaranh profile image
Smaran Harihar

Please continue the series.

Collapse
 
freakcdev297 profile image
FreakCdev

Sure man!

Collapse
 
aidenybai profile image
Aiden Bai

cool stuff!

Collapse
 
freakcdev297 profile image
FreakCdev

cool!

Collapse
 
luizc91 profile image
LuizC91 • Edited

Is there a possibility of you teach us how to do it in another language?
Before I forget: thank you for the post. It will help me a lot.

Collapse
 
freakcdev297 profile image
FreakCdev

I picked Javascript because it's pretty widely used and easy. I might write some variations of this in different languages and upload it to the JeChain repository on Github. In the mean time, I think you can try to write your own by following the concepts mentioned in the article :D

Collapse
 
luizc91 profile image
LuizC91

I will do.

Collapse
 
emilienbidet profile image
Emilien Bidet

Thank you for your work, I will try it

Collapse
 
freakcdev297 profile image
FreakCdev

Thanks man! New posts will come out soon, hope you'll check them out until then!!!

Collapse
 
careuno profile image
Carlos Merchán

continue please

Collapse
 
coderduck profile image
duccanhole

good post! from vietnam with love

Collapse
 
opauloh profile image
Paulo Henrique

Very nice article!

Collapse
 
ronaldohoch profile image
Ronaldo Hoch

Thank you a lot for the article!
I think you can keep doing this as a serie here and continue to write a full crypto currency 😁

Collapse
 
freakcdev297 profile image
FreakCdev

Definitely!

Collapse
 
robyconte profile image
Roberto Conte Rosito

Great post!
It helps me better understanding this topic. Thank you for your sharing!

Collapse
 
freakcdev297 profile image
FreakCdev

Glad I could help!

Collapse
 
cnitish profile image
cnitish

Thank you for this article. Appreciate this effort.

Please, if possible, kindly write about Non- Fungible Tokens and full cryptocurrency.

Cheers.

Collapse
 
hieultimate profile image
hieultimate

great post there

Collapse
 
bvince77 profile image
bvince77

This is interesting. I've wanted to read up on this to get some basic understanding. Great article

Collapse
 
noxklax profile image
Nox Klax

This is awesome! It helps me to understand a little bit better what's happening under the hood.

Collapse
 
dariozz profile image
Dario Mendez

Marvelous to deep understand blockchain, I would like to suggest the smart contracts version

Collapse
 
walteralvar profile image
WalterAlvar

Wow, I am also student but definitely gonna study this

Collapse
 
bolonhadev profile image
Bolonha Dev

Dope

Collapse
 
mguimaraes16 profile image
Marcello Guimarães

Nice job bro, can I open a Pull request coding a c# version of your code?

Collapse
 
freakcdev297 profile image
FreakCdev

Sure!

Collapse
 
andrewinsoul profile image
Okoye Andrew

Thanks for this masterpiece 🙏🙏

Collapse
 
andrescass profile image
Andres Cassagnes

Excellent post. Please continue the series, maybe with proof of stake, which I think is the logical following post.
Thank you for the post

Collapse
 
freakcdev297 profile image
FreakCdev

Thanks! I'm planning to write a proof-of-stake system soon!

Collapse
 
uche_azubuko profile image
Uchechukwu Azubuko

I really enjoyed this piece @freakcdev297

Collapse
 
jesanhe profile image
jesanhe

This article helped me to better understand Blockchain on an easy way. Great work!! Please continue writing this series.

Collapse
 
aryaanish121 profile image
Arya Anish

Can you please make a full cryptocurrency tutorial?

Collapse
 
freakcdev297 profile image
FreakCdev

Your welcome, stay tuned because I will release new articles about blockchain soon!

Collapse
 
freakcdev297 profile image
FreakCdev

Have just updated a system to calculate mining difficulty!

Collapse
 
subhadas01 profile image
Subha_das01

Pliz create a topic about node.js

Collapse
 
quinnj102 profile image
quinnj102

Writing and deploying contracts (token contract, MasterChef) in solidity, creating a front end and Connecting the front end Dapp (yield farm) to the blockchain with web3JS.

Collapse
 
thechallengerr profile image
thechallengerr

bài viết hay quá a ơi