(ESP|ENG) Como crear tu propia blockchain con Javascript y NodeJs?, Acá te enseño un poco. || How to create your own blockchain with Javascript and NodeJs? Here I will show you a bit.

in LeoFinance3 years ago

Primero que nada, ¿Qué es una Blockchain?

First of all, what is a Blockchain?

Blockchain-glosario-workana-850x400.jpg

  • Imagen: Workana || Image: Workana

Una cadena de bloques, o mejor conocida como Blockchain, es un registro único, distribuido y consensuado en varios nodos de una red. En el caso de las criptomonedas, podemos pensarlo como el libro contable donde se registran cada una de las transacciones.

A chain of blocks, or better known as Blockchain, is a single, distributed and consensual registry in several nodes of a network. In the case of cryptocurrencies, we can think of it as the ledger where each of the transactions are recorded.

Mas información Aquí

Bien, ahora pasemos al codigo

Ok, now let's move on to the code

Nota: Debemos instalar NodeJs, depende de tu sistema operativo, acá deberás descargar el que corresponda con tu ordenador

Note: We must install NodeJs, it depends on your operating system, here you must download the one that corresponds to your computer

1 - Crearemos una carpeta donde almacenaremos el código a desarrollar, ustedes pueden colocarle el nombre que prefieran, yo en mi caso la llamaré "Blockchain", dentro de la misma crearemos un archivo con el nombre main.js.

1 - We will create a folder where we will store the code to be developed, you can put the name you prefer, in my case I will call it "Blockchain", within it we will create a file with the name main.js.

2 - Ahora con el editor de nuestra preferencia, abriremos nuestra carpeta.

2 - Now with the editor of our preference, we will open our folder.

Screenshot_44.png

3 - Nuevamente crearemos otro archivo que llevará por nombre Block.js, en este archivo escribiremos nuestro código para la elaboración de toda la función que tendrá nuestra Blockchain.

3 - Again we will create another file that will be named Block.js, in this file we will write our code for the elaboration of all the function that our Blockchain will have.

Screenshot_45.png

4 - En este archivo escribiremos lo siguiente:

4 - In this file we will write the following:

  • Crearemos una clase llamada Block con la declaración "export", que se utiliza al crear módulos en Javascript para exportar funciones, objetos o tipos de datos primitivos, con esta declaración desde nuestro archivo main.js llamaremos las funciones de nuestro archivo Block.js.
  • We will create a class called Block with the declaration "export", which is used when creating modules in Javascript to export functions, objects or primitive data types, with this declaration from our file main.js we will call the functions of our Block.js file.
export class Block {
    constructor(index = 0, previousHash = null, data, difficulty = 1 ){
        this.index = index;
        this.previousHash = previousHash;
        this.data = data;
        this.timestamp = new Date()
        this.difficulty = difficulty;
        this.nonce = 0;

        this.mine()
    }

    generateHash(){
        
    }

    mine(){
        
    }

}

  • A continuación abriremos una consola de comando en la carpeta "Blockchain" y iniciaremos el comando:
  • Next we will open a command console in the "Blockchain" folder and we will start the command:
npm init

ahí nos pedirá la información correspondiente a nuestro proyecto, sería algo asi:

there it will ask us for the information corresponding to our project, it would be something like this:

Screenshot_47.png

y nos creara un archivo en nuestra carpeta así.

and create a file in our folder like this.
Screenshot_48.png

  • Luego de eso, en la misma consola ejecutaremos el siguiente comando:
npm install --save crypto-js

y nos saldría y quedaría algo así:

Screenshot_49.png

Screenshot_50.png

  • Ya de haber instalado la biblioteca "crypto-js", crearemos una constante llamada SHA256, que requiere de 'crypto-js/sha256', así mismo está realizara la función de generar el hash para nuestros bloques.
  • Having already installed the "crypto-js" library, we will create a constant called SHA256, which requires 'crypto-js/sha256', and it will also perform the function of generating the hash for our blocks.
  • Agregamos a nuestro codigo, lo siguiente.
  • We add the following to our code.
import { sha256 } from "crypto-js/sha256";

export class Block {
    constructor(index = 0, previousHash = null, data, difficulty = 1 ){
        this.index = index;
        this.previousHash = previousHash;
        this.data = data;
        this.timestamp = new Date()
        this.difficulty = difficulty;
        this.nonce = 0;

        this.mine()
    }

    generateHash(){
        return sha256(this.index, this.previousHash + JSON.stringify(this.data) + this.timestamp + this.nonce)
    }

    mine(){
        this.hash = this.generateHash()

        while(!(/^0*$/.test(this.hash.substring(0, this.difficulty)))){
            this.nonce++
            this.hash = this.generateHash()
        }
    }

}
  • La función generateHash se usa para dar a cada bloque su propio hash, esta función toma cada pieza del objeto Block, así mismo lanzandola en una función SHA256 convirtiéndola en una cadena.
  • The generateHash function is used to give each block its own hash, this function takes each piece of the Block object, as well as throwing it into a SHA256 function, turning it into a string.
  • La siguiente función mine se utilizará para procesar con seguridad las transacciones en la red de nuestra Blockchain, añadiéndoles dificultad al proceso de generado del hash, de tal manera, la dificultad será el numero de ceros con el que iniciara el hash.
  • The following mine function will be used to safely process the transactions in our Blockchain network, adding difficulty to the process of generating the hash, in such a way, the difficulty will be the number of zeros with which the hash will start.

Screenshot_54.png

  • Ahora intentamos probar nuestra Blockchain y nos arrojara este error:
  • Now we try to test our Blockchain and it will throw us this error:

Screenshot_51.png

Pero, este error se debe a una configuración que debemos hacer en nuestro package.json, una pequeña línea de código que debemos añadir, lo cual sería lo siguiente.

But, this error is due to a configuration that we must do in our package.json, a small line of code that we must add, which would be the following.

"type": "module",

Y nos quedaria algo así.

And we would have something like this.

{
  "name": "blockchain",
  "type": "module", // Linea a añadir || Line to add.
  "version": "0.1.0",
  "description": "Blockchain en javascript",
  "main": "main.js",
  "scripts": {
    "test": "run test"
  },
  "keywords": [
    "Blockchain",
    "educativo"
  ],
  "author": "Frederick Barrios",
  "license": "ISC",
  "dependencies": {
    "crypto-js": "^4.0.0"
  }
}

Ahora debemos agregar esta línea de código

Now we must add this line of code

import pkg from 'crypto-js/sha256.js';
const sha256 = pkg;

en la cabecera de nuestro archivo Block.js, así como esta en la imgen n°8, para que no haya problemas al momento de importar la función para generar el hash.

in the header of our Block.js file, as well as in image n ° 8, so that there are no problems when importing the function to generate the hash.

  • Ahora procedemos a la creación de otro archivo en nuestra carpeta con el nombre de Blockchain.js, en este archivo copiaremos lo siguiente:
  • Now we proceed to the creation of another file in our folder with the name of Blockchain.js, in this file we will copy the following:
import { Block } from "./Block.js";

export class Blockchain{
    constructor(difficulty = 0){
        this.blocks = [new Block()]
        this.index = 1
        this.difficulty = difficulty
    }

    getLastBlock(){
        return this.blocks[this.blocks.length - 1]
    }

    addBlock(data){
        const index = this.index;
        const difficulty = this.difficulty;
        const previousHash = this.getLastBlock().hash

        const block = new Block(index, previousHash, data, difficulty)

        this.index++
        this.blocks.push(block)
    }

    isValid(){
        for (let i = 1; i < this.blocks.length; i++) {
            const currentBlock = this.blocks[i]
            const previousBlock = this.blocks[i - 1]

            if (currentBlock.hash !== currentBlock.generateHash()) {
                return false
            }

            if (currentBlock.index !== previousBlock.index + 1) {
                return false
            }

            if (currentBlock.previousHash !== previousBlock.hash) {
                return false
            }
        }
        return true
    }
}

Acá crearemos otra clase llamada Blockchain, con la misma declaración "export", arriba explique la función de esta declaración.

Here we will create another class called Blockchain, with the same "export" declaration, above explain the function of this declaration.

  • La función getLastBlock obtendrá de nuestra red Blockchain si hubo o no un bloque anterior obteniendo así los datos del mismo, así como el hash, tiempo de minado, dificultad y recompensa.
  • The getLastBlock function will obtain from our Blockchain network whether or not there was a previous block, thus obtaining its data, as well as the hash, mining time, difficulty and reward.
  • La función addBlock se encargará de verificar que el nuevo bloque a agregar sea compatible con la red, gracias a la ayuda de la función getLastBlock obteniendo así el hash del bloque anterior, para poder así agregar el nuevo bloque minado.
  • The addBlock function will be in charge of verifying that the new block to be added is compatible with the network, thanks to the help of the getLastBlock function, thus obtaining the hash of the previous block, in order to add the new one mined block.
  • La siguiente y ultima función isValid, se encargará de verificar toda la red y confirmar que la cadena de bloques este en perfecto estado y no corrupto.
  • The next and last function isValid, will be in charge of verifying the entire network and confirming that the blockchain is in perfect condition and not corrupt.

Screenshot_55.png

  • Ya llegando a la parte final de la elaboración de nuestra Blockchain en Javascript, nos iremos a nuestro primer archivo main.js y copiaremos lo siguiente:
  • Already reaching the final part of the development of our Blockchain in Javascript, we will go to our first file main.js and copy the following:
import { Blockchain } from "./Blockchain.js";

const blockchain = new Blockchain()
blockchain.addBlock({ amount: 4 })
blockchain.addBlock({ amount: 50 })

console.log(blockchain)

console.log(blockchain.isValid())
blockchain.blocks[1].data.amount = 30000
console.log(blockchain.isValid())

Y con este código llamaremos las funciones de nuestra cadena de bloques.

And with this code we will call the functions of our blockchain.

  • Ahora en la consola de comandos en la ruta de nuestra carpeta, iniciaremos nuestra Blockchain de la siguiente manera:
  • Now in the command console in the path of our folder, we will start our Blockchain as follows:
node main.js
  • Nos debería arrojar este resultado:
  • It should give us this result:
Blockchain {
  blocks: [
    Block {
      index: 0,
      previousHash: null,
      data: 'Genesis Block',
      timestamp: 2021-05-26T02:23:17.299Z,
      difficulty: 0,
      nonce: 0,
      hash: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'
    },
    Block {
      index: 1,
      previousHash: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
      data: [Object],
      timestamp: 2021-05-26T02:23:17.309Z,
      difficulty: 0,
      nonce: 0,
      hash: '4ea5c508a6566e76240543f8feb06fd457777be39549c4016436afda65d2330e'
    },
    Block {
      index: 2,
      previousHash: '4ea5c508a6566e76240543f8feb06fd457777be39549c4016436afda65d2330e',
      data: [Object],
      timestamp: 2021-05-26T02:23:17.311Z,
      difficulty: 0,
      nonce: 0,
      hash: '4ea5c508a6566e76240543f8feb06fd457777be39549c4016436afda65d2330e'
    }
  ],
  index: 3,
  difficulty: 0
}
true
true

Screenshot_56.png

¡Y Voila!, ya tenemos nuestra blockchain, o al menos su estructura, pronto estaré compartiendo otro post añdiendo a nuestra cadena de bloques una wallet con la que podamos almacenar las recompensas obtenidas.

And Voila !, we already have our blockchain, or at least its structure, I will soon be sharing another post adding a wallet to our blockchain with which we can store the rewards obtained.

Espero que haya sido muy interesante, entrenido, educativo, y sobre todo que les haya gustado.

I hope it was very interesting, trained, educational, and above all that you liked it.

Eutherum150px.png

Sort:  

Buen post tienes mi voto!!

Posted Using LeoFinance Beta

Muchas gracias !! 😁

Excelente publicación 👌🏻💪🏻💪🏻 felicidades

Gracias !! 😁

Congratulations @frederickac! You have completed the following achievement on the Hive blockchain and have been rewarded with new badge(s) :

You received more than 100 upvotes.
Your next target is to reach 200 upvotes.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Support the HiveBuzz project. Vote for our proposal!