SlideShare a Scribd company logo
Node.js Blockchain Implementation
Node.js Blockchain Implementation
Valerii Radchenko
JS TechTalk #2
17.08.2018
The Blockchain
Wikipedia says:
A blockchain, originally block chain, is a growing list of records, called
blocks, which are linked using cryptography.
The Blockchain
Wikipedia says:
A blockchain, originally block chain, is a growing list of records, called
blocks, which are linked using cryptography.
The blockchain is a way of storing data for free access and making changes
that are safe, confirmed by most users in an open distributed network.
Examples and tools
• As an example, we will look at very simplified cryptocurrency
implementation.
• Tools and modules:
- Node.js
- Typescript
- Crypto (Node.js core module)
- Elliptic (npm package)
- Base58, big-integer(npm package)
- levelUp, levelDown (npm packages)
Agenda
1. Basic Concept
2. Persistence
3. Proof Of Work
4. Addresses
5. Transactions
6. Mining
7. More
8. Conclusion
7
Basic Concept
Blocks
• In blockchain, its blocks store valuable information.
• Besides this, a block contains some technical information, like:
- Version
- Current timestamp
- Its hash
- Hash of the previous block
Block
Schema Code
Block Hash
• One of the important thing in a blockchain is calculating hashes.
- It makes blockchain secure.
- Calculating hashes requires some time even on powerful computers.
- This is an intentional architectural design, which makes adding new blocks
difficult, thus preventing their modification after they’re added.
Block Hash
Schema Code
Blockchain
• Blockchain is a database structure: it’s an ordered, back-linked list.
• Which means that blocks are stored in the insertion order and that each
block is linked to the previous one. This structure allows to quickly get the
latest block in a chain and to get a block by its hash.
Blockchain
Genesis block
• In any blockchain, there must be at least one block.
• The first block in the chain is called the genesis block and creating a
blockchain must start by creating such block.
Node.js Blockchain Implementation
16
Persistence
What kind of database fit our needs?
• We need a simple serverless database to store our blocks one after another
- NoSQL
- Serverless
- Key/value or documented
- Simple and fast
Databases
• LevelDB
• LiteDB
• VelocityDB
• And many more…
BitcoinCore Database Structure
• 'l' -> 4-byte file number: the last block file number used
• 'c' + 32-byte transaction hash -> unspent transaction output record for that
transaction
• 32-byte block hash -> block record
• The full database structure description
Node.js Blockchain Implementation
21
Proof Of Work
Proof Of Work
• A proof of work is a piece of data which is difficult (costly, time-consuming)
to produce but easy for others to verify and which satisfies certain
requirements.
• Producing a proof of work can be a random process with low probability so
that a lot of trial and error is required on average before a valid proof of
work is generated.
Nonce and Complexity
"Hello, world!0" => 1312af178c253f84028d480a6adc1e25e81caa44c749ec81976192e2ec934c64
"Hello, world!1" => e9afc424b79e4f6ab42d99c81156d3a17228d6e1eef4139be78e948a9332a7d8
"Hello, world!2" => ae37343a357a8297591625e7134cbea22f5928be8ca2a32aa475cf05fd4266b7
...
"Hello, world!4248" =>
6e110d98b388e77e9c6f042ac6b497cec46660deef75a55ebc7cfdf65cc0b965
"Hello, world!4249" =>
c004190b822f1669cac8dc37e761cb73652e7832fb814565702245cf26ebb9e6
"Hello, world!4250" => 0000c3af42fc31103f1fdc0151fa747ff87349a4714df7cc52ea464e12dcd4e9
Node.js Blockchain Implementation
Node.js Blockchain Implementation
26
Addresses
Bitcoin Address
• 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa This is the very first Bitcoin
address
• Addresses are not something that identifies you as the owner of a “wallet”
• Address is a public key
• In Bitcoin, your identity is a pair of private and public keys stored on your
computer
Node.js Blockchain Implementation
Public-key Cryptography
• Digital Signatures guarantee:
- Data wasn’t modified while being transferred from a sender to a recipient
- Data was created by a certain sender
- The sender cannot deny sending the data
• In order to sign data we need:
- Data to sign
- Private key
• In order to verify a signature:
- Data that was signed
- The signature
- Public key
Node.js Blockchain Implementation
Node.js Blockchain Implementation
Node.js Blockchain Implementation
33
Demo Time
34
Transactions
Transactions
• No accounts
• No balances
• No addresses
• No coins
• No senders and receivers
Node.js Blockchain Implementation
Node.js Blockchain Implementation
Miners
• Miners are nodes are run on powerful or specialized hardware (like ASIC),
and their only goal is to mine new blocks as fast as possible. Miners are
only possible in blockchains that use Proof-of-Work
The Coinbase Transaction
• In Bitcoin, outputs come before inputs.
• When a miner starts mining a block, it adds a coinbase transaction to it. A
coinbase transaction is a special type of transactions, which doesn’t require
previously existing outputs. It creates outputs out of nowhere.
Node.js Blockchain Implementation
• Every block must store at least one
transaction and it’s no more possible to mine
blocks without transactions.
Storing Transactions in Blockchain
Change
• Each output might be used only once. This means that once an input got a
reference to an output the output cannot be used again even if its value is
higher then needed to create a transaction. In this case, we create
additional output in which value we place a difference between transaction
amount and referenced output value. It is a change.
Unspent Transaction Outputs (Balance)
• Unspent means that these outputs weren’t referenced in any inputs
- tx0, output 1
- tx1, output 0
- tx3, output 0
- tx4, output 0
• When we check balance, we need only those that can be unlocked by the
key we own.
Node.js Blockchain Implementation
Sending Coins
• We want to send some coins to someone else. For this, we need to create
a new transaction, put it in a block, and mine the block.
• Before creating new outputs, we first have to find all unspent outputs and
ensure that they store enough value.
The UTXO Set
• Cause, we could have tons of blocks, we do not want to iterate through all
of them. And UTXO Set can help us avoid this.
Node.js Blockchain Implementation
Node.js Blockchain Implementation
Node.js Blockchain Implementation
Node.js Blockchain Implementation
Merkle Tree
• The full Bitcoin database (i.e., blockchain) takes more than 282 Gb of disk
space
• Because of the decentralized nature of Bitcoin, every node in the network
must be independent and store a full copy of the blockchain
Merkle Tree And Simplified Payment Verification (SPV)
• SPV is a light Bitcoin node that doesn’t download the whole blockchain and
doesn’t verify blocks and transactions. Instead, it finds transactions in
blocks (to verify payments) and is linked to a full node to retrieve just
necessary data. This mechanism allows having multiple light wallet nodes
with running just one full node.
Node.js Blockchain Implementation
Node.js Blockchain Implementation
55
Mining
56
Demo Time
57
More…
Important things
• Networking
• Mining on GPU
• Smart contracts (P2PKH)
59
Conclusion
Conclusion
• Node.js is a great platform for creating P2P networks, easy coding your
blockchain applications and a big amount of various crypto functions.
• But there are some cons:
- Very slow mining performance
- There is no ability to use GPU without workarounds
Helpful Links
• BitcoinCore Wiki
• Blockchain on Go
• Bitcoin Explorer
• GitHub ValeriyRadchenko
Thank you
Node.js Blockchain Implementation
Ad

Recommended

PPTX
Azure Unchained (Azure boot camp Sofia 2017)
Valio Bonev
 
PDF
Parity Progress Report
gavofyork
 
PDF
Introduction to the Nancy Framework
Tim Bourguignon
 
PDF
JavaOne 2016 - Reactive Microservices with Java and Java EE
Rodrigo Cândido da Silva
 
PPTX
vlavrynovych - WebSockets Presentation
Volodymyr Lavrynovych
 
PDF
GUJavaSC - Criando Micro-serviços Reativos com Java
Rodrigo Cândido da Silva
 
PDF
Encode polkadot club
Vanessa Lošić
 
PDF
Digital Forensics and Incident Response in The Cloud
Velocidex Enterprises
 
PPTX
Vulnerability intelligence with vulners.com / Кирилл Ермаков, Игорь Булатенко...
Ontico
 
PDF
Ускоряем загрузку картинок вебсокетами
2ГИС Технологии
 
PPTX
Altitude SF 2017: Fastly GSLB: Scaling your microservice and multi-cloud envi...
Fastly
 
PDF
Openstack Keystone
Kamesh Pemmaraju
 
PDF
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
PROIDEA
 
PPTX
Azure Blockchain Workbench
Murughan Palaniachari
 
PDF
Altitude SF 2017: Logging at the edge
Fastly
 
PDF
WILD microSERVICES v2 (JEEConf Edition)
Aleksandr Tarasov
 
PDF
Microservices with Spring
Software Infrastructure
 
PDF
Control Plane: Continuous Kubernetes Security (DevSecOps - London Gathering, ...
Michael Man
 
PDF
DockerCon Live 2020 - Securing Your Containerized Application with NGINX
Kevin Jones
 
PPTX
Resource slides for blockchain related question
Lin Lin (Wendy)
 
PDF
Reactive Architectures
Ralph Winzinger
 
PDF
HashiCorp Vault Workshop:幫 Credentials 找個窩
smalltown
 
PDF
Securing Microservices using Play and Akka HTTP
Rafal Gancarz
 
PDF
Issuing temporary credentials for my sql using hashicorp vault
OlinData
 
PPTX
Developing Business Blockchain Applications on Hyperledger
IMC Institute
 
PDF
Altitude SF 2017: Optimizing your hit rate
Fastly
 
PDF
Managing secrets at scale
Alex Schoof
 
PDF
Blockchain, bitcoin
Sathish VJ
 
PPTX
Introduction to Blockchain
Sanjeev Mishra
 

More Related Content

What's hot (20)

PPTX
Vulnerability intelligence with vulners.com / Кирилл Ермаков, Игорь Булатенко...
Ontico
 
PDF
Ускоряем загрузку картинок вебсокетами
2ГИС Технологии
 
PPTX
Altitude SF 2017: Fastly GSLB: Scaling your microservice and multi-cloud envi...
Fastly
 
PDF
Openstack Keystone
Kamesh Pemmaraju
 
PDF
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
PROIDEA
 
PPTX
Azure Blockchain Workbench
Murughan Palaniachari
 
PDF
Altitude SF 2017: Logging at the edge
Fastly
 
PDF
WILD microSERVICES v2 (JEEConf Edition)
Aleksandr Tarasov
 
PDF
Microservices with Spring
Software Infrastructure
 
PDF
Control Plane: Continuous Kubernetes Security (DevSecOps - London Gathering, ...
Michael Man
 
PDF
DockerCon Live 2020 - Securing Your Containerized Application with NGINX
Kevin Jones
 
PPTX
Resource slides for blockchain related question
Lin Lin (Wendy)
 
PDF
Reactive Architectures
Ralph Winzinger
 
PDF
HashiCorp Vault Workshop:幫 Credentials 找個窩
smalltown
 
PDF
Securing Microservices using Play and Akka HTTP
Rafal Gancarz
 
PDF
Issuing temporary credentials for my sql using hashicorp vault
OlinData
 
PPTX
Developing Business Blockchain Applications on Hyperledger
IMC Institute
 
PDF
Altitude SF 2017: Optimizing your hit rate
Fastly
 
PDF
Managing secrets at scale
Alex Schoof
 
Vulnerability intelligence with vulners.com / Кирилл Ермаков, Игорь Булатенко...
Ontico
 
Ускоряем загрузку картинок вебсокетами
2ГИС Технологии
 
Altitude SF 2017: Fastly GSLB: Scaling your microservice and multi-cloud envi...
Fastly
 
Openstack Keystone
Kamesh Pemmaraju
 
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
PROIDEA
 
Azure Blockchain Workbench
Murughan Palaniachari
 
Altitude SF 2017: Logging at the edge
Fastly
 
WILD microSERVICES v2 (JEEConf Edition)
Aleksandr Tarasov
 
Microservices with Spring
Software Infrastructure
 
Control Plane: Continuous Kubernetes Security (DevSecOps - London Gathering, ...
Michael Man
 
DockerCon Live 2020 - Securing Your Containerized Application with NGINX
Kevin Jones
 
Resource slides for blockchain related question
Lin Lin (Wendy)
 
Reactive Architectures
Ralph Winzinger
 
HashiCorp Vault Workshop:幫 Credentials 找個窩
smalltown
 
Securing Microservices using Play and Akka HTTP
Rafal Gancarz
 
Issuing temporary credentials for my sql using hashicorp vault
OlinData
 
Developing Business Blockchain Applications on Hyperledger
IMC Institute
 
Altitude SF 2017: Optimizing your hit rate
Fastly
 
Managing secrets at scale
Alex Schoof
 

Similar to Node.js Blockchain Implementation (20)

PDF
Blockchain, bitcoin
Sathish VJ
 
PPTX
Introduction to Blockchain
Sanjeev Mishra
 
PPTX
IEEE ICDM 2018 Tutorial on Blockchain Data Analytics
Cuneyt Gurcan Akcora
 
PPTX
Idea To IPO Blockchain Slides
Roger Royse
 
PDF
Blockchain Fundamental_KIPMI_2022.02.26.pdf
adinugroho751867
 
PPTX
Blockchain Future & Investments 2018 - Women in Product
Aarthi Srinivasan
 
PPTX
A Quick Start To Blockchain by Seval Capraz
Seval Çapraz
 
PPTX
Blockchain
NikolaMatijaevi
 
PDF
Blockchain Technology
Mohammaderfan Arefimoghaddam
 
PPTX
Introduction to Blockchain
subbul
 
PDF
Introduction into blockchains and cryptocurrencies
Sergey Ivliev
 
PDF
Blockchain - a formal introduction
Sander Demeester
 
PDF
The presentation on the Blockchain_Introduction_KR.pdf
nehapatil1600
 
PPTX
PRESENTATION.pptx
FaiZiTricks
 
PPTX
BlockchainConf.tech - Build a private blockchain workshop
Pad Kankipati
 
PPT
BlockChain_and _cryptocurrency_technology (1).ppt
FaiZiTricks
 
PDF
Introduction to Blockchain
Muhammad Moinur Rahman
 
PDF
Click Ventures Blockchain Ecosystem Report 2018
Frederick Ng
 
PDF
Introduction to Blockchains
RameshNair6
 
PPTX
BLOCKCHAIN PPT.pptx
SohanaAmreen
 
Blockchain, bitcoin
Sathish VJ
 
Introduction to Blockchain
Sanjeev Mishra
 
IEEE ICDM 2018 Tutorial on Blockchain Data Analytics
Cuneyt Gurcan Akcora
 
Idea To IPO Blockchain Slides
Roger Royse
 
Blockchain Fundamental_KIPMI_2022.02.26.pdf
adinugroho751867
 
Blockchain Future & Investments 2018 - Women in Product
Aarthi Srinivasan
 
A Quick Start To Blockchain by Seval Capraz
Seval Çapraz
 
Blockchain
NikolaMatijaevi
 
Blockchain Technology
Mohammaderfan Arefimoghaddam
 
Introduction to Blockchain
subbul
 
Introduction into blockchains and cryptocurrencies
Sergey Ivliev
 
Blockchain - a formal introduction
Sander Demeester
 
The presentation on the Blockchain_Introduction_KR.pdf
nehapatil1600
 
PRESENTATION.pptx
FaiZiTricks
 
BlockchainConf.tech - Build a private blockchain workshop
Pad Kankipati
 
BlockChain_and _cryptocurrency_technology (1).ppt
FaiZiTricks
 
Introduction to Blockchain
Muhammad Moinur Rahman
 
Click Ventures Blockchain Ecosystem Report 2018
Frederick Ng
 
Introduction to Blockchains
RameshNair6
 
BLOCKCHAIN PPT.pptx
SohanaAmreen
 
Ad

More from GlobalLogic Ukraine (20)

PDF
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic Ukraine
 
PPTX
Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)
GlobalLogic Ukraine
 
PDF
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Ukraine
 
PDF
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Ukraine
 
PDF
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Ukraine
 
PDF
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic Ukraine
 
PPTX
Штучний інтелект як допомога в навчанні, а не замінник.pptx
GlobalLogic Ukraine
 
PPTX
Задачі AI-розробника як застосовується штучний інтелект.pptx
GlobalLogic Ukraine
 
PPTX
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
GlobalLogic Ukraine
 
PDF
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Ukraine
 
PDF
JavaScript Community Webinar #14 "Why Is Git Rebase?"
GlobalLogic Ukraine
 
PDF
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic Ukraine
 
PPTX
Страх і сила помилок - IT Inside від GlobalLogic Education
GlobalLogic Ukraine
 
PDF
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic Ukraine
 
PDF
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic Ukraine
 
PDF
“How to Secure Your Applications With a Keycloak?
GlobalLogic Ukraine
 
PDF
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Ukraine
 
PPTX
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Ukraine
 
PDF
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic Ukraine
 
PDF
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
GlobalLogic Ukraine
 
GlobalLogic JavaScript Community Webinar #21 “Інтерв’ю без заспокійливих”
GlobalLogic Ukraine
 
Deadlocks in SQL - Turning Fear Into Understanding (by Sergii Stets)
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #18 “How to Improve Web Application Perfor...
GlobalLogic Ukraine
 
GlobalLogic Embedded Community x ROS Ukraine Webinar "Surgical Robots"
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #17 “SpringJDBC vs JDBC. Is Spring a Hero?”
GlobalLogic Ukraine
 
GlobalLogic JavaScript Community Webinar #18 “Long Story Short: OSI Model”
GlobalLogic Ukraine
 
Штучний інтелект як допомога в навчанні, а не замінник.pptx
GlobalLogic Ukraine
 
Задачі AI-розробника як застосовується штучний інтелект.pptx
GlobalLogic Ukraine
 
Що треба вивчати, щоб стати розробником штучного інтелекту та нейромереж.pptx
GlobalLogic Ukraine
 
GlobalLogic Java Community Webinar #16 “Zaloni’s Architecture for Data-Driven...
GlobalLogic Ukraine
 
JavaScript Community Webinar #14 "Why Is Git Rebase?"
GlobalLogic Ukraine
 
GlobalLogic .NET Community Webinar #3 "Exploring Serverless with Azure Functi...
GlobalLogic Ukraine
 
Страх і сила помилок - IT Inside від GlobalLogic Education
GlobalLogic Ukraine
 
GlobalLogic .NET Webinar #2 “Azure RBAC and Managed Identity”
GlobalLogic Ukraine
 
GlobalLogic QA Webinar “What does it take to become a Test Engineer”
GlobalLogic Ukraine
 
“How to Secure Your Applications With a Keycloak?
GlobalLogic Ukraine
 
GlobalLogic Machine Learning Webinar “Advanced Statistical Methods for Linear...
GlobalLogic Ukraine
 
GlobalLogic Machine Learning Webinar “Statistical learning of linear regressi...
GlobalLogic Ukraine
 
GlobalLogic C++ Webinar “The Minimum Knowledge to Become a C++ Developer”
GlobalLogic Ukraine
 
Embedded Webinar #17 "Low-level Network Testing in Embedded Devices Development"
GlobalLogic Ukraine
 
Ad

Recently uploaded (20)

PDF
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
PPTX
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
PDF
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
PDF
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
PPTX
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
PDF
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
PDF
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
PDF
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
PPTX
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
PDF
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
PPTX
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
PDF
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
PDF
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
PDF
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
PDF
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
PDF
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
PDF
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
PDF
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
PDF
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
PPTX
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
9-1-1 Addressing: End-to-End Automation Using FME
Safe Software
 
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
From Manual to Auto Searching- FME in the Driver's Seat
Safe Software
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 

Node.js Blockchain Implementation

  • 2. Node.js Blockchain Implementation Valerii Radchenko JS TechTalk #2 17.08.2018
  • 3. The Blockchain Wikipedia says: A blockchain, originally block chain, is a growing list of records, called blocks, which are linked using cryptography.
  • 4. The Blockchain Wikipedia says: A blockchain, originally block chain, is a growing list of records, called blocks, which are linked using cryptography. The blockchain is a way of storing data for free access and making changes that are safe, confirmed by most users in an open distributed network.
  • 5. Examples and tools • As an example, we will look at very simplified cryptocurrency implementation. • Tools and modules: - Node.js - Typescript - Crypto (Node.js core module) - Elliptic (npm package) - Base58, big-integer(npm package) - levelUp, levelDown (npm packages)
  • 6. Agenda 1. Basic Concept 2. Persistence 3. Proof Of Work 4. Addresses 5. Transactions 6. Mining 7. More 8. Conclusion
  • 8. Blocks • In blockchain, its blocks store valuable information. • Besides this, a block contains some technical information, like: - Version - Current timestamp - Its hash - Hash of the previous block
  • 10. Block Hash • One of the important thing in a blockchain is calculating hashes. - It makes blockchain secure. - Calculating hashes requires some time even on powerful computers. - This is an intentional architectural design, which makes adding new blocks difficult, thus preventing their modification after they’re added.
  • 12. Blockchain • Blockchain is a database structure: it’s an ordered, back-linked list. • Which means that blocks are stored in the insertion order and that each block is linked to the previous one. This structure allows to quickly get the latest block in a chain and to get a block by its hash.
  • 14. Genesis block • In any blockchain, there must be at least one block. • The first block in the chain is called the genesis block and creating a blockchain must start by creating such block.
  • 17. What kind of database fit our needs? • We need a simple serverless database to store our blocks one after another - NoSQL - Serverless - Key/value or documented - Simple and fast
  • 18. Databases • LevelDB • LiteDB • VelocityDB • And many more…
  • 19. BitcoinCore Database Structure • 'l' -> 4-byte file number: the last block file number used • 'c' + 32-byte transaction hash -> unspent transaction output record for that transaction • 32-byte block hash -> block record • The full database structure description
  • 22. Proof Of Work • A proof of work is a piece of data which is difficult (costly, time-consuming) to produce but easy for others to verify and which satisfies certain requirements. • Producing a proof of work can be a random process with low probability so that a lot of trial and error is required on average before a valid proof of work is generated.
  • 23. Nonce and Complexity "Hello, world!0" => 1312af178c253f84028d480a6adc1e25e81caa44c749ec81976192e2ec934c64 "Hello, world!1" => e9afc424b79e4f6ab42d99c81156d3a17228d6e1eef4139be78e948a9332a7d8 "Hello, world!2" => ae37343a357a8297591625e7134cbea22f5928be8ca2a32aa475cf05fd4266b7 ... "Hello, world!4248" => 6e110d98b388e77e9c6f042ac6b497cec46660deef75a55ebc7cfdf65cc0b965 "Hello, world!4249" => c004190b822f1669cac8dc37e761cb73652e7832fb814565702245cf26ebb9e6 "Hello, world!4250" => 0000c3af42fc31103f1fdc0151fa747ff87349a4714df7cc52ea464e12dcd4e9
  • 27. Bitcoin Address • 1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa This is the very first Bitcoin address • Addresses are not something that identifies you as the owner of a “wallet” • Address is a public key • In Bitcoin, your identity is a pair of private and public keys stored on your computer
  • 29. Public-key Cryptography • Digital Signatures guarantee: - Data wasn’t modified while being transferred from a sender to a recipient - Data was created by a certain sender - The sender cannot deny sending the data • In order to sign data we need: - Data to sign - Private key • In order to verify a signature: - Data that was signed - The signature - Public key
  • 35. Transactions • No accounts • No balances • No addresses • No coins • No senders and receivers
  • 38. Miners • Miners are nodes are run on powerful or specialized hardware (like ASIC), and their only goal is to mine new blocks as fast as possible. Miners are only possible in blockchains that use Proof-of-Work
  • 39. The Coinbase Transaction • In Bitcoin, outputs come before inputs. • When a miner starts mining a block, it adds a coinbase transaction to it. A coinbase transaction is a special type of transactions, which doesn’t require previously existing outputs. It creates outputs out of nowhere.
  • 41. • Every block must store at least one transaction and it’s no more possible to mine blocks without transactions. Storing Transactions in Blockchain
  • 42. Change • Each output might be used only once. This means that once an input got a reference to an output the output cannot be used again even if its value is higher then needed to create a transaction. In this case, we create additional output in which value we place a difference between transaction amount and referenced output value. It is a change.
  • 43. Unspent Transaction Outputs (Balance) • Unspent means that these outputs weren’t referenced in any inputs - tx0, output 1 - tx1, output 0 - tx3, output 0 - tx4, output 0 • When we check balance, we need only those that can be unlocked by the key we own.
  • 45. Sending Coins • We want to send some coins to someone else. For this, we need to create a new transaction, put it in a block, and mine the block. • Before creating new outputs, we first have to find all unspent outputs and ensure that they store enough value.
  • 46. The UTXO Set • Cause, we could have tons of blocks, we do not want to iterate through all of them. And UTXO Set can help us avoid this.
  • 51. Merkle Tree • The full Bitcoin database (i.e., blockchain) takes more than 282 Gb of disk space • Because of the decentralized nature of Bitcoin, every node in the network must be independent and store a full copy of the blockchain
  • 52. Merkle Tree And Simplified Payment Verification (SPV) • SPV is a light Bitcoin node that doesn’t download the whole blockchain and doesn’t verify blocks and transactions. Instead, it finds transactions in blocks (to verify payments) and is linked to a full node to retrieve just necessary data. This mechanism allows having multiple light wallet nodes with running just one full node.
  • 58. Important things • Networking • Mining on GPU • Smart contracts (P2PKH)
  • 60. Conclusion • Node.js is a great platform for creating P2P networks, easy coding your blockchain applications and a big amount of various crypto functions. • But there are some cons: - Very slow mining performance - There is no ability to use GPU without workarounds
  • 61. Helpful Links • BitcoinCore Wiki • Blockchain on Go • Bitcoin Explorer • GitHub ValeriyRadchenko