Skip to content

Commit

Permalink
Step 1: A chain of blocks?
Browse files Browse the repository at this point in the history
  • Loading branch information
nambrot committed Nov 12, 2017
0 parents commit 761c267
Show file tree
Hide file tree
Showing 20 changed files with 7,611 additions and 0 deletions.
22 changes: 22 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# See https://help.github.com/ignore-files/ for more about ignoring files.

# dependencies
/node_modules

# testing
/coverage

# production
/build
/screencaps

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Build your own Blockchain in Javascript

With all the hype about blockchains and cryptocurrencies, I decided to learn a bit more about it. And what better way to learn than to try to build it? Here you will find my attempts to build blockchains from their basic principles, and hopefully in the process it helps someone else to learn something from this as well. Let's get started

## Step 1: A chain of blocks?

To understand how blockchains work, let's start with the name. Blockchain? A chain of blocks?

A common misconception is that a blockchain is a single chain of blocks, when in reality, it's more like a tree of blocks. So at any given time, there are multiple chains for blocks by pointing to their respective parent. The pointing happens via hashes which are calculated based upon the data inside the block (i.e. hash of the parent, transaction data and other important stuff)

By pointing via hashes of blocks, we can enforce a specific order of blocks. I.e given a chain of blocks, you can't just take a block in the middle of the chain and change its data, since that would change its hash and subsequently also all blocks that are descendents of the block in question.

```javascript
class Block {
constructor(blockchain, parentHash, nonce = sha256(new Date().getTime().toString()).toString()) {
this.blockchain = blockchain;
this.nonce = nonce;
this.parentHash = parentHash;
this.hash = sha256(this.nonce + this.parentHash).toString()
}
```
If you look at the code, you can see how the P2P aspect of blockchains comes into play. Once a node decided it "mined" a block, it can broadcast that block to all other nodes, you can verify it and then add it to their tree, as well.
![blockbroadcast](https://user-images.githubusercontent.com/571810/32704273-37b7b07a-c7d0-11e7-900c-851031c81ad4.gif)
25 changes: 25 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "blockchain-js",
"version": "0.1.0",
"private": true,
"dependencies": {
"@blueprintjs/core": "^1.32.0",
"@blueprintjs/labs": "^0.12.0",
"crypto-js": "^3.1.9-1",
"express": "^4.16.2",
"ramda": "^0.25.0",
"react": "^16.1.0",
"react-addons-css-transition-group": "^15.6.2",
"react-dom": "^16.1.0",
"react-scripts": "1.0.17",
"react-sortable-tree": "^1.5.0",
"socket.io": "^2.0.4",
"socket.io-client": "^2.0.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
Binary file added public/favicon.ico
Binary file not shown.
40 changes: 40 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
15 changes: 15 additions & 0 deletions public/manifest.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": "./index.html",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
30 changes: 30 additions & 0 deletions src/App.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
@import "../node_modules/@blueprintjs/core/dist/blueprint.css";

.App {
text-align: center;
}

.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 80px;
}

.App-header {
background-color: #222;
height: 150px;
padding: 20px;
color: white;
}

.App-title {
font-size: 1.5em;
}

.App-intro {
font-size: large;
}

@keyframes App-logo-spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
69 changes: 69 additions & 0 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import React, { Component } from 'react';
import './App.css';
import BlockchainWelcome from './components/BlockchainWelcome'
import { Button } from "@blueprintjs/core";
import { action } from './store';

class App extends Component {
state = {
ownBlockchainName: ''
}
pickBlockchain = (name) => {
action({ type: 'PICK_BLOCKCHAIN', name })
}
render() {
return (
<div className="">
<nav className='pt-navbar'>
<div className="pt-navbar-group pt-align-left">
<div className="pt-navbar-heading">Build your own Blockchain</div>
</div>

<div className="pt-navbar-group pt-align-right">
<select
onChange={(evt) => {
this.pickBlockchain(evt.target.value)
}}
value={this.props.appState.selectedBlockchain ? this.props.appState.selectedBlockchain.name : ''}
>
{
[<option key='default' value=''>Pick a blockchain or</option>].concat(this.props.appState.blockchains.map((b) => <option key={b.name} value={b.name}>{b.name}</option>))
}
</select>

<div className='pt-control-group'>
<div className='pt-input-group'>
<input
className='pt-input'
placeholder="create your own"
value={this.state.ownBlockchainName}
style={{paddingRight: '150px'}}
onChange={(evt) => this.setState({ownBlockchainName: evt.target.value})}
/>
<div className="pt-input-action">
<Button
text='Create'
onClick={() => this.pickBlockchain(this.state.ownBlockchainName)}
/>
</div>
</div>
</div>
</div>
</nav>
<div className="container" style={{padding: 24}}>
{ this.props.appState.selectedBlockchain === undefined &&
<p>
Learn more about blockchains. Start by picking or create a new blockchain in the top-right corner.
</p>
}
{
this.props.appState.selectedBlockchain !== undefined &&
<BlockchainWelcome blockchain={this.props.appState.selectedBlockchain} />
}
</div>
</div>
);
}
}

export default App;
8 changes: 8 additions & 0 deletions src/App.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
});
43 changes: 43 additions & 0 deletions src/components/BlockchainWelcome.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import React, { Component } from 'react';
import SortableTree from 'react-sortable-tree';
import {getTreeFromFlatData} from 'react-sortable-tree';
import {Button} from '@blueprintjs/core';

class BlockchainWelcome extends Component {
state = {
treeData: [{ title: 'Chicken', children: [ { title: 'Egg' } ] }],
}
render() {
const treeData = getTreeFromFlatData({
flatData: Object.values(this.props.blockchain.blocks),
getKey: (block) => block.hash,
getParentKey: (block) => block.parentHash,
rootKey: this.props.blockchain.genesis.parentHash
});
return (
<div>
<div style={{height: 800}}>
<SortableTree
treeData={treeData}
canDrag={false}
onChange={treeData => this.setState({ treeData })}
generateNodeProps={({ node, path }) => ({
buttons: [
<Button
text='Add block from here'
onClick={() => {
const block = this.props.blockchain.blocks[node.hash]
block.addChild();
}}
/>
]
})}
/>
</div>
</div>
)

}
}

export default BlockchainWelcome;
5 changes: 5 additions & 0 deletions src/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
14 changes: 14 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@

import {action, state} from './store';
import {subscribeTo, publish} from './network'
action({})

subscribeTo('BLOCKCHAIN_BROADCAST', (names) => {
action({ type: 'BLOCKCHAIN_BROADCAST', names })
})

subscribeTo('BLOCKCHAIN_BROADCAST_REQUEST', () => {
publish('BLOCKCHAIN_BROADCAST', state.blockchains.map((b) => b.name))
})

publish('BLOCKCHAIN_BROADCAST_REQUEST', {})
7 changes: 7 additions & 0 deletions src/logo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
32 changes: 32 additions & 0 deletions src/models/Block.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import sha256 from 'crypto-js/sha256';

class Block {
constructor(blockchain, parentHash, nonce = sha256(new Date().getTime().toString()).toString()) {
this.blockchain = blockchain;
this.nonce = nonce;
this.parentHash = parentHash;
this.hash = sha256(this.nonce + this.parentHash).toString()

// for visualization purposes
this.title = `Block ${this.hash.substr(0, 10)}`;
this.expanded = true;
}

addChild() {
this.blockchain.addBlock(this);
}

toJSON() {
return {
hash: this.hash,
nonce: this.nonce,
parentHash: this.parentHash
}
}
}

export default Block;

export function fromJSON(blockchain, data) {
return new Block(blockchain, data.parentHash, data.nonce)
}
50 changes: 50 additions & 0 deletions src/models/Blockchain.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import Block from './Block';
import {fromJSON} from './Block';
import {rerender} from "../store";
import {publish, subscribeTo} from "../network";

class Blockchain {
constructor(name) {
this.name = name;
this.genesis = null;
this.blocks = {};

this.createGenesisBlock();

subscribeTo('BLOCKS_BROADCAST', ({ blocks, blockchainName }) => {
if (blockchainName === this.name) {
blocks.forEach(block => this._addBlock(fromJSON(this, block)))
}
})

publish('REQUEST_BLOCKS', { blockchainName: this.name })
subscribeTo('REQUEST_BLOCKS', ({ blockchainName }) => {
if (blockchainName === this.name)
publish('BLOCKS_BROADCAST', { blockchainName, blocks: Object.values(this.blocks).map(b => b.toJSON())})
})
}

createGenesisBlock() {
const block = new Block(this, 'root', this.name);
this.blocks[block.hash] = block;
this.genesis = block;
}

containsBlock(block) {
return this.blocks[block.hash] !== undefined
}

addBlock(parent) {
const newBlock = new Block(this, parent.hash);
this._addBlock(newBlock)
publish('BLOCKS_BROADCAST', { blocks: [newBlock.toJSON()], blockchainName: this.name })
}

_addBlock(block) {
if (!this.containsBlock(block)) {
this.blocks[block.hash] = block;
rerender()
}
}
}
export default Blockchain;
Loading

0 comments on commit 761c267

Please sign in to comment.