---
# System prepended metadata

title: "<center>BigchainDB \U0001F4BE</center>"
tags: [Master's Thesis]

---

# <center>BigchainDB 💾</center>

###### tags: `Master's Thesis`

**Name : Ian, Graciela, & Yohanes**
<br>
[toc]


---
## <center>What is BigchainDB?</center>
:::info
BigchainDB is called a blockchain database because it has some blockchain properties and some database properties. The original design started with a database and added some blockchain characteristics such as decentralization, immutability, and owner-controlled assets. The idea was that the resulting system would inherit the desirable properties of the database such as low latency, high transaction rate and high capacity.
<br>
picture below illustrates some ways BigchainDB could be used in various technology stacks.
<br>
![](https://i.imgur.com/GrTXbdB.png)
reference : [**bigchainDB whitepapper**](https://www.bigchaindb.com/whitepaper/)
:::
<br>

---
## <center>Purpose</center>
:::info
1. Storing data in the blockchain requires mining cost, which will be increased along with the data size. 
2. In the EHR use case, pictures also on of the item that needs to be stored in the database. 
3. Storing picture in database will be **slow** and **expensive**. 
4. Hence, we need a decentralized database to store a large size data. So the storing process could be **faster** and **costless**.
:::

<br>

---
## <center>Operation Guide</center>
BigchainDB is a javascript-based application. So, node.js server is needed to operate this database. The development of this part could be checked in this [Github repository](https://github.com/ianjoseph2204/Healthcoin_DDB).

### 1. Installation
:::info
1.  Install [**node.js**](https://nodejs.org/en/download/)
2.  Open terminal & install BigchainDB using the command below:
    ```shell
    npm install bigchaindb-driver
    ```
    Output:
    ![](https://i.imgur.com/VKE8MLA.png)

:::

### 2. Setup
:::info
1. **Database Setup** 
```javascript=
const driver = require('bigchaindb-driver') //import the bigchainDB library

// BigchainDB server instance or testnetwork (e.g. https://example.com/api/v1/)
const API_PATH = [
    'http://192.168.1.13:9984/api/v1/'
]

//connection with BDB
const conn = new driver.Connection(API_PATH)
```

:::

---
## <center>BigchainDB Core API</center>
bigchainDB has several core API functions. In this note, I will only use 3 API function to operate the bigchainDB

### 1. Create User
:::info
```javascript=
// Create a new keypair for Alice and Bob
const alice = new driver.Ed25519Keypair()
const bob = new driver.Ed25519Keypair()

console.log('Public Key Alice :', alice.publicKey)
console.log('private Key Alice :', alice.privateKey)
console.log('public Key Bob :', bob.publicKey)
console.log('private key Bob :', bob.privateKey)
```
:::


### 2. Data Format
:::info
BigChainDB using JSON format data to in the data process. Here is an example to store a bicycle data with its serial number and manufacturer

```javascript=
const assetdata = {
    'bicycle': {
            'serial_number': 'abcd1234',
            'manufacturer': 'Bicycle Inc.',
    }
}
```

<br>
if you have more information about the transaction itself, you can put metadata

```javascript=
// (can be `null` if not needed)
// E.g. the bicycle is fabricated on earth
const metadata = {'planet': 'earth'}
```

:::success
With this format, we could store the original EHR data along with the metadata in the BigchainDB
:::
### 3. Create Transaction
:::info
Create transaction is the storing process of the data & metadata that we created on the previous section.

This function can be used to register, issue, create or otherwise initiate the history of a single thing (or asset) in BigchainDB.
:::
```javascript=
const txCreateAliceSimple = driver.Transaction.makeCreateTransaction(
    assetdata, // Put the original bicycle data
    metadata, // Put the bicycle metadata

    // A receipt output for the transaction
    [ driver.Transaction.makeOutput(
            driver.Transaction.makeEd25519Condition(alice.publicKey))
    ],
    alice.publicKey
)

const txCreateAliceSimpleSigned = driver.Transaction.signTransaction(txCreateAliceSimple, alice.privateKey)

console.log('Transaction ID :',txCreateAliceSimpleSigned)

conn.postTransactionCommit(txCreateAliceSimpleSigned)
```
:::info
**Explanation**:
1. Create a transaction of Alice Bicycle (line 1-9)
2. signed the transaction with Alice private key (line 12)
3. Check the information of alice transaction (line 14)
4. Send the transaction into BigchainDB node (line 16)
:::

**Output**:
![](https://i.imgur.com/hBl2o7b.png)


<!-- ### 4. Transfer Transaction
```javascript=
const txTransferBob = driver.Transaction.makeTransferTransaction(
    // signedTx to transfer and output index
    [{ tx: txCreateAliceSimpleSigned, output_index: 0 }],
    [driver.Transaction.makeOutput(driver.Transaction.makeEd25519Condition(bob.publicKey))],
    // metadata
    { price: '100 euro' }
)

// Sign with alice's private key
let txTransferBobSigned = driver.Transaction.signTransaction(txTransferBob, alice.privateKey)
console.log('Posting signed transaction: ', txTransferBobSigned)

// Post with commit so transaction is validated and included in a block
return conn.postTransactionCommit(txTransferBobSigned)


console.log('Response from BDB server:', tx)
console.log('Is Bob the owner?', tx['outputs'][0]['public_keys'][0] == bob.publicKey)
console.log('Was Alice the previous owner?', tx['inputs'][0]['owners_before'][0] == alice.publicKey)
```

Output:
![](https://i.imgur.com/zbWI6Sy.png)

:::info
**explanation**:
1. In the code above, i try to transfer the data from Alice to Bob with Bob public key with additional metadata price 100euro (line 1-7), and i need to signed the transaction with alice private key (line 9-11)
2.  i also post the transaction in bigchaindb (line 14)
3.  I tried to query the data of about whos the owner the data and check about "was alice the previous owner" (line 17-19)

::: -->

## <center>BigchainDB Simulation</center>
:::warning
**Notes**:
BigchainDB has provided the Docker image for simulation purpose. The simulation environment:
- Local networks (No proxy & external connection)
- 2 PCs with Windows OS 
:::

### 1. Install the BigchainDB Requirements:
:::warning
**Software requirements**:
1. WSL 2
2. Docker Desktop
3. Ubuntu
:::

#### 1.1 Setup WSL 2
:::info
**Notes**:
WSL 2 is needed for the Docker Desktop & Ubuntu for environment virtualization on Windows.
1. Enable Windows virtualization on BIOS.
2. Open Powershell as administrator.
3. Enable the Windows subsystem for Linux with the command below:
    ```
    dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
    ```
    Result:
    ![](https://i.imgur.com/ZEcDEdf.png)
4. Enable the virtual machine feature with the command below:
    ```
    dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
    ```
    Result:
    ![](https://i.imgur.com/FWrRI1M.png)
5. Download & install the [**Linux kernel update package**](https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi).
6. Set WSL 2 as the default version with the command below:
    ```
    wsl --set-default-version 2
    ```
    Result:
    ![](https://i.imgur.com/nIGqgPR.png)
7. Restart your PC to finish configuration.
:::


#### 1.2 Setup Docker Desktop
:::info
Docker is needed for running the BigchainDB image on Ubuntu
1. Install [**Docker Desktop**](https://docs.docker.com/desktop/windows/install/) for Windows:
![](https://i.imgur.com/dqdxP4i.png)
2. Setup the WSL 2 configuration on Docker Desktop:
    - Open Docker Desktop settings (<i class="fa fa-gear"></i> icon)
    - Setup the General settings:
        ![](https://i.imgur.com/B0YoPbs.png)
    - Setup the Resources settings:
        ![](https://i.imgur.com/cb2rxbU.png)
:::


#### 1.3 Setup Ubuntu Windows
:::info 
**Notes**:
We need to use "make" library on Linux to run the bigchainDB Docker image.
1. Install the [**Ubuntu**](https://www.microsoft.com/en-us/p/ubuntu/9nblggh4msv6#activetab=pivot:overviewtab) for Windows
![](https://i.imgur.com/RLQGzwF.png)
1. Setup your Windows ubuntu username & password (I set  mined as ijosh2204):
![](https://i.imgur.com/ZnhsM2l.png)
1. Install "make" library for ubuntu:
    ```
    sudo apt-get update
    
    # Install the "make" library
    sudo apt-get install make
    
    # Check the version of "make" library
    make -v
    ```
    **Output**:
    ![](https://i.imgur.com/TLCrXNb.png)
:::


### 2. Setup BigchainDB server:
:::info
1. Open the Ubuntu
2. Clone the bigchaindb image from Github
    ```
    git clone https://github.com/bigchaindb/bigchaindb.git
    ```
    **Output**:
    ![](https://i.imgur.com/PY3szkF.png)
3. Run the bigchainDB docker image on "bigchaindb" folder
    ```
    cd bigchaindb 
    sudo make run
    ```
    **Output**:
    ![](https://i.imgur.com/fMcDSG9.png)
4. Test connection to bigchain node from browser
    ```
    localhost:9984
    ```
    :::success
    **Output**:
    ![](https://i.imgur.com/sWqJqjm.png)
    **Explanation**:
    If bigchaindb node is succeeded running on the PC, the information above will be appeared on the browser.
:::

<!-- 
### 3. Create Transaction simmulation
:::info

**PC 1**

test.js script
```javascript=
const driver = require('bigchaindb-driver')

const API_PATH = 'http://192.168.1.16:9984/api/v1/'

const conn = new driver.Connection(API_PATH)

const assetdata = {
    'bicycle': {
            'serial_number': 'abcd1234',
            'manufacturer': 'Bicycle Inc.',
    }
}

const metadata = {'planet': 'earth'}

const txCreateAliceSimple = driver.Transaction.makeCreateTransaction(
    assetdata,
    metadata,

    [driver.Transaction.makeOutput(
 driver.Transaction.makeEd25519Condition(alice.publicKey))
    ],
    alice.publicKey
)

const txCreateAliceSimpleSigned = driver.Transaction.signTransaction(txCreateAliceSimple, alice.privateKey)

conn.postTransactionCommit(txCreateAliceSimpleSigned)
        .then(retrievedTx => console.log('Transaction', retrievedTx.id, 'successfully posted.'))

        .then(() => {
                const txTransferBob = driver.Transaction.makeTransferTransaction(

                        [{ tx: txCreateAliceSimpleSigned, output_index: 0 }],
                        [driver.Transaction.makeOutput(driver.Transaction.makeEd25519Condition(bob.publicKey))],
                        {price: '100 euro'}
                )

                let txTransferBobSigned = driver.Transaction.signTransaction(txTransferBob, alice.privateKey)
                console.log('Posting signed transaction: ', txTransferBobSigned)

                return conn.postTransactionCommit(txTransferBobSigned)
        })
        .then(tx => {
                console.log('Response from BDB server:', tx)
                console.log('Is Bob the owner?', tx['outputs'][0]['public_keys'][0] == bob.publicKey)
                console.log('Was Alice the previous owner?', tx['inputs'][0]['owners_before'][0] == alice.publicKey )
        })
         
         .then(() => conn.searchAssets('Bicycle Inc.'))
         .then(assets => console.log('Found assets with serial number Bicycle Inc.:', assets))
```

Output:
![](https://i.imgur.com/Ve0kovQ.png)


**Explanation**: 
1. i do the same thing like i make transaction before,  i try to created transaction of Alice Bicycle (line 15-21), signed the transaction with Alice private key in line 24, i try to transfer the data from Alice to Bob with Bob public key with additional metadata price 100euro (line 28-37), and i need to signed the transaction with alice private key (line 39-40), and I tried to query the data of alice transaction (line 44-51) 

<br>
<br>
:::

:::info
**PC 2**
i tried code same like pc 1 to track the transaction

output:
![](https://i.imgur.com/GeHGW8Y.png)

Explanation:
1. for the sync test, i using the same code for PC1 to make the transaction on localhost API, in the output we all know that transactions made on PC1 after checking are still in PC2 terminal.
:::
 -->
:::success
**Summary**:
The sync feature of bigchainDB is proven worked, because we could extract the transaction from PC 2 that has been created on PC 1. 
:::