An open API service indexing awesome lists of open source software.

https://github.com/aymen94/simple-blockchain

small tutorial with code to try to create your blockchain 🔝
https://github.com/aymen94/simple-blockchain

blockchain javascript learn tutorial typescript

Last synced: about 1 month ago
JSON representation

small tutorial with code to try to create your blockchain 🔝

Awesome Lists containing this project

README

        

# How to Work BlockChain
how to work blockchain, this is only example structure. :smiley:

small tutorial with code to try to create your blockchain.

I used typescript because is very easy to read/understand.

-----------------------------------------------------------------------------------------------------

## Block.ts

### Instance variable
- index ===> index block.

- timestamp ===> date of block instance.

- data ===> any type of data to save in block

- precedentHash ===>hash of the last block (lock added before this block).

- hashBlock ===> hash of this block.

- nonce ===>it has nothing to do with blocking, change to something random (example random number).

#### constructor block
```
public constructor(index,data)
```

#### methods of the block.
```
public getHashBlock();

public getprecedentHash();

public setPrecedentHash(hash);

public generateHash();

```

> Proof-of-work is used to make secure the blockchain(similar bitcoin Hashcash)

> more info https://en.wikipedia.org/wiki/Proof-of-work_system
```
public mineBlock(miningDifficulty:number){
while(this.hashBlock.substring(0,miningDifficulty)!=Array(miningDifficulty+1).join('0')){
this.nonce++;
this.generateHash();
}
```

-----------------------------------------------------------------------------------------------------------
## BlockChain.ts
### Instance variable
- chain:Array ===> array of block,(better chained list).
- miningDifficulty ===> the difficulty of mining expressed in numbers(the more the number is high the more the difficulty increases).

#### constructor BlockChain
> as a parameter it takes the difficulty of mining.
> when to start the blockchain, add the first block (this block is without the previous hash block because is the first block)
```
constructor(miningD){
this.chain=new Array(new Block(0,{ firstBlock:"Created By Aymen Naghmouchi"}));
this.miningDifficulty=miningD;
}
```

#### methods of the BlockChain.
```
public getLastBlock();

public checkBlockChain();

```

> set the precedent block hash in the last added and regenerate her hash
```
public addBlock(newBlock){
newBlock.setPrecedentHash(this.getLastBlock().getHashBlock());
newBlock.mineBlock(this.miningDifficulty);
this.chain.push(newBlock);
}
```
![Alt text](https://raw.githubusercontent.com/aymen94/simple-Blockchain/master/blockchain-aymen%20.jpg?raw=true "Blockchain")

> check all blocks are linked among them.
```

public checkBlockChain():boolean{
for(let i:number=1;i