Skip to content

Praktikum Blockchain: Implementasi dengan JavaScript (Edisi Linux up to 2.4)

Klik link berikut untuk melihat sumber asli Referensi Praktikum Blockchain

Dokumen ini berisi panduan langkah-demi-langkah untuk membangun blockchain sederhana menggunakan Node.js di sistem operasi Linux.

1. Setup Environment

Sebelum memulai implementasi, kita perlu menyiapkan lingkungan pengembangan.

1.1 Instalasi Node.js (Metode NVM)

Di Linux, sangat disarankan menggunakan NVM (Node Version Manager) untuk mengelola versi Node.js.

  1. Buka terminal (Ctrl+Alt+T).
  2. Instal NVM (jika belum ada):

    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
    
    OR for the latest version
    curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/master/install.sh | bash
    

  3. Instal Node.js versi LTS:

    nvm install --lts
    

  4. Verifikasi instalasi:
    node -v
    npm -v
    

1.2 Struktur Proyek

Buat direktori kerja untuk proyek blockchain Anda:

mkdir -p ~/Blockchain/src
mkdir -p ~/Blockchain/test
cd ~/Blockchain

Inisialisasi proyek NPM:

npm init -y

1.3 Instalasi Visual Studio Code

Untuk pengguna Linux, Anda bisa menginstal VS Code via snap atau paket manager:

sudo snap install --classic code

OR you can just use your favorite IDE.

2. Struktur Data Blockchain

2.1 Menginstal Modul SHA256

Kita membutuhkan algoritma hashing untuk mengamankan blok:

npm install sha256

2.2 Membuat File src/blockchain.js

Berikut adalah implementasi lengkap class Block dan Blockchain berdasarkan isi panduan (Poin 2.2 - 2.3.6 PDF):

const sha256 = require('sha256');

class Block {
  constructor(index, timestamp, nonce, prevBlockHash, hash, transactions) {
    this.index = index;
    this.timestamp = timestamp;
    this.transactions = transactions;
    this.nonce = nonce;
    this.hash = hash;
    this.prevBlockHash = prevBlockHash;
  }
}

class Blockchain {
  constructor() {
    this.chain = [];
    this.pendingTransactions = [];
    // Membuat Genesis Block
    this.createNewBlock(100, '0', 'Genesis block');
  }

  createNewBlock(nonce, prevBlockHash, hash) {
    const newBlock = new Block(
      this.chain.length + 1,
      Date.now(),
      nonce,
      prevBlockHash,
      hash,
      this.pendingTransactions
    );
    this.pendingTransactions = [];
    this.chain.push(newBlock);
    return newBlock;
  }

  getLatestBlock() {
    return this.chain[this.chain.length - 1];
  }

  makeNewTransaction(amount, sender, recipient) {
    const transaction = {
      amount: amount,
      sender: sender,
      recipient: recipient
    };

    this.pendingTransactions.push(transaction);
    console.log(`>>> Transaction: ${amount} from ${sender} to ${recipient}`);

    return this.getLatestBlock().index + 1;
  }

  hashBlock(prevBlockHash, currentBlock, nonce) {
    const data = prevBlockHash + JSON.stringify(currentBlock) + nonce;
    const hash = sha256(data);
    return hash;
  }

  proofOfWork(prevBlockHash, currentBlockData) {
    let nonce = 0;
    let hash = this.hashBlock(prevBlockHash, currentBlockData, nonce);
    while (hash.substring(0, 2) !== '00') {
      nonce++;
      hash = this.hashBlock(prevBlockHash, currentBlockData, nonce);
    }
    return nonce;
  }
}

module.exports = Blockchain;

2.3 Pengujian Logika Blockchain (Console Test)

Sebelum masuk ke API, kita harus memastikan logika blockchain berjalan benar. Buat file test/blockchain.js:

const Blockchain = require('../src/blockchain');

const bitcoin = new Blockchain();

// 1. Tambahkan transaksi pending
bitcoin.makeNewTransaction(100, 'ALICE', 'BOB');

// 2. Simulasi Mining
console.log('>>> Mining block 2...');
const lastBlock = bitcoin.getLatestBlock();
const prevBlockHash = lastBlock.hash;
const currentBlockData = {
  transactions: bitcoin.pendingTransactions,
  index: lastBlock.index + 1
};

const nonce = bitcoin.proofOfWork(prevBlockHash, currentBlockData);
const blockHash = bitcoin.hashBlock(prevBlockHash, currentBlockData, nonce);

bitcoin.createNewBlock(nonce, prevBlockHash, blockHash);

console.log('>>> Current Blockchain Data:');
console.log(JSON.stringify(bitcoin, null, 4));

Jalankan di terminal:

node test/blockchain.js

3. Implementasi Blockchain API

3.1 Instalasi Express & Nodemon

npm install express body-parser nodemon

Edit package.json, tambahkan script start:

"scripts": {
  "start": "nodemon --watch src -e js src/api.js"
}

3.2 Membuat API Endpoints (src/api.js)

const express = require('express');
const app = express();
const Blockchain = require('./blockchain');
const bitcoin = new Blockchain();

app.use(express.json());

app.get('/blockchain', (req, res) => {
  res.send(bitcoin);
});

app.post('/transaction', (req, res) => {
  const blockIndex = bitcoin.makeNewTransaction(
    req.body.amount, 
    req.body.sender, 
    req.body.recipient
  );
  res.json({ message: `Transaction is added to block with index: ${blockIndex}` });
});

app.get('/mine', (req, res) => {
  const lastBlock = bitcoin.getLatestBlock();
  const prevBlockHash = lastBlock.hash;
  const currentBlockData = {
    transactions: bitcoin.pendingTransactions,
    index: lastBlock.index + 1
  };
  const nonce = bitcoin.proofOfWork(prevBlockHash, currentBlockData);
  const blockHash = bitcoin.hashBlock(prevBlockHash, currentBlockData, nonce);

  // Reward untuk miner
  bitcoin.makeNewTransaction(1, '00000', 'miner-node-1');

  const newBlock = bitcoin.createNewBlock(nonce, prevBlockHash, blockHash);

  res.json({
    message: "Mining new Block successfully!",
    newBlock: newBlock
  });
});

app.listen(3000, () => console.log('Server listening on port 3000...'));

4. Pengujian dengan Postman di Linux

4.1 Menjalankan Server

Jalankan perintah berikut di terminal:

npm start

4.2 Tutorial Pengujian Postman

  1. Cek Blockchain (GET):

    • URL: http://localhost:3000/blockchain
    • Method: GET
    • Klik Send. Anda harus melihat Genesis Block.
  2. Tambah Transaksi (POST):

    • URL: http://localhost:3000/transaction
    • Method: POST
    • Klik Tab Body -> Pilih raw -> Pilih JSON.
    • Masukkan data berikut:
      {
        "amount": 50,
        "sender": "IPUNG",
        "recipient": "ARIF"
      }
      
    • Klik Send. Pastikan mendapat balasan "Transaction is added...".
  3. Lakukan Mining (GET):

    • URL: http://localhost:3000/mine
    • Method: GET
    • Klik Send. Blok baru akan tercipta.
  4. Cek Hasil Akhir:

    • Panggil kembali GET /blockchain untuk melihat blok baru yang berisi transaksi tadi.

4.3 Tips Linux (Troubleshooting)

Jika muncul error EADDRINUSE: address already in use :::3000, artinya port 3000 masih dipakai proses lama. Gunakan perintah ini untuk mematikannya:

# Cari PID proses yang memakai port 3000
lsof -i :3000

# Matikan proses (ganti <PID> dengan angka yang muncul di kolom PID)
kill -9 <PID>