[PYTHON] Experience blockchain with BigchainDB

At first, I read the articles around here and caught up. https://www.slideshare.net/cookle/5-58379474 http://qiita.com/hshimo/items/1881fba8957c2a6e17ca http://qiita.com/akitoh/items/bebf1bf3d71d3e4b96b0

So I found the blockchain to be very useful.

I only know roughly, but I want to move it anyway. If you make a mistake, please rush in. Try using a library called bigchaindb that I've been interested in for a long time. It says it's a scalable blockchain db. A library that combines distributed DB and blockchain, not just pure p2p.

--Official https://docs.bigchaindb.com/en/latest/index.html

BigchainDB use case

Tracking property assets along the licensing chain

BigchainDB reduces license competition for channels that connect creators and viewers, providing a perfect investment in digital artifacts. A typical music service has 38 million songs. BigchainDB can store this information in a heartbeat, as well as license information for each song and information about subscriber usage. As another example, consider a medium-sized photo market that runs 100,000 transactions a day. Applying this to Bitcoin costs $ 10,000 per day and connects to the Bitcoin network.

Receipt and certificate.

BigchainDB reduces legal friction by providing irrefutable evidence of electronic behavior. BigchainDB can also store support information such as receipts and certificates (COA) directly, rather than linking to documents or storing hashes.

Abbreviation ~

https://www.thoughtworks.com/insights/blog/blockchain-practice-tamper-proof-read-receipts

Difference from traditional block chain

It does not connect with the previous block with a hash. A voting list is kept inside the block. The signing node votes. It will be valid if you get a majority of the votes in favor of the block. And a chain occurs at the time of voting.

スクリーンショット 2017-08-30 21.12.20.png

Terminology

BigchainDB Node A BigchainDB node is a set of machines running a MongoDB server, a BigchainDB server. Each node is controlled by an individual or organization. BigchainDB Cluster A set of BigchainDB nodes can be interconnected to form a BigchainDB cluster. Each node in the cluster runs the same software. The cluster contains one logical MongoDB datastore. BigchainDB Consortium The people and organizations that run the nodes in the cluster belong to the BigchainDB Consortium (another organization). The consortium needs a governance structure to make decisions. If a company operates a cluster, that company is the only "consortium". A cluster is a collection of connected nodes. A consortium is an organization that has a cluster and each node in the cluster has a different operator. What is an operator ... Anyway, it is interpreted as an image with a cluster under the consortium and a node under the cluster.

Document structure

スクリーンショット 2017-08-19 3.20.30.png

At a higher level, you can use the BigchainDB Client-Server HTTP API, or a wrapper for that API (such as the BigchainDB Python Driver), to communicate with a BigchainDB cluster (a set of nodes). The BigchainDB Python Driver supports preparing, executing, and sending transactions to BigchainDB nodes. Get transaction by id. Get the transaction status by id.

Server side: server docs, server quickstart, http api docs Client side: python driver docs Others: comannd line tran ... tool

environment

ubuntu14 or mac python3 conda DB chooses RethinkDB or MongoDB, is RethinkDB still supported?

BigchainDB Server settings

This is a server-side setting.

Install around python environment

It doesn't work unless it's python3, so I switched to python3 with conda.

Click here for conda http://qiita.com/miyamotok0105/items/5f26e4ae41f0e35ded16

sudo apt-get update
sudo apt-get install g++ python3-dev libffi-dev build-essential libssl-dev
sudo apt-get install python3-pip
sudo pip3 install --upgrade pip setuptools
sudo pip3 install bigchaindb
bigchaindb -y configure mongodb

put mongo 3.4 or above

https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/

First of all, here is mongo. It's a JSON-based db, and you can throw it in without thinking about the type. http://qiita.com/saba1024/items/f2ad56f2a3ba7aaf8521

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6
echo "deb [ arch=amd64 ] http://repo.mongodb.org/apt/ubuntu precise/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list
sudo apt-get update
sudo apt-get install -y mongodb-org
mongo --version
sudo mkdir -p /data/db
sudo chmod -R 700 /data/db

Setting

If you are running on a server, change the ip or domain part

sudo emacs ~/.bigchaindb

"server": {"bind": "localhost:9984", ... } to "server": {"bind": "0.0.0.0:9984", ... }

0.0.0.0 to your server information

reference https://docs.bigchaindb.com/projects/server/en/latest/production-nodes/setup-run-node.html

Start-up

Start MongoDB

sudo mongod --replSet=bigchain-rs

This resulted in an error. If you don't, you can skip it. The mongo I put in before is in the way. Solved below. http://kiita312.hatenablog.com/entry/2013/03/03/130935

Set up another console with bigchain-rs running.

Start BigchainDB Server

bigchaindb start

A log comes out and moves. This. This guy will work.

****************************************************************************
*                                                                          *
*   Initialization complete. BigchainDB Server is ready and waiting.       *
*   You can send HTTP requests via the HTTP API documented in the          *
*   BigchainDB Server docs at:                                             *
*    https://bigchaindb.com/http-api                                       *
*                                                                          *
*   Listening to client connections on: localhost:9984                     *
*                                                                          *
****************************************************************************
 (MainProcess - pid: 15547)
======== Running on http://localhost:9985 ========
(Press CTRL+C to quit)
[2017-08-19 02:47:02] [INFO](gunicorn.error) Starting gunicorn 19.7.1 (webapi     - pid: 15680)
[2017-08-19 02:47:02] [INFO](gunicorn.error) Listening at: http://127.0.0.1:9984 (15680) (webapi     - pid: 15680)
[2017-08-19 02:47:02] [INFO](gunicorn.error) Using worker: sync (webapi     - pid: 15680)
[2017-08-19 02:47:02] [INFO](gunicorn.error) Booting worker with pid: 15685 (webapi     - pid: 15685)
[2017-08-19 02:47:02] [INFO](gunicorn.error) Booting worker with pid: 15686 (webapi     - pid: 15686)
[2017-08-19 02:47:02] [INFO](gunicorn.error) Booting worker with pid: 15687 (webapi     - pid: 15687)
[2017-08-19 02:47:02] [INFO](gunicorn.error) Booting worker with pid: 15688 (webapi     - pid: 15688)
[2017-08-19 02:47:03] [INFO](gunicorn.error) Booting worker with pid: 15689 (webapi     - pid: 15689)
[2017-08-19 02:47:07] [INFO](bigchaindb.backend.mongodb.connection) Closing initial connection to MongoDB (Process-16 - pid: 15659)


Access the part of localhost: 9984.

If you hit it with a browser, something will come back

{
  "api": {
    "v1": {
      "assets": "/api/v1/assets/", 
      "docs": "https://docs.bigchaindb.com/projects/server/en/v1.0.1/http-client-server-api.html", 
      "outputs": "/api/v1/outputs/", 
      "statuses": "/api/v1/statuses/", 
      "streams": "ws://localhost:9985/api/v1/streams/valid_transactions", 
      "transactions": "/api/v1/transactions/"
    }
  }, 
  "docs": "https://docs.bigchaindb.com/projects/server/en/v1.0.1/", 
  "keyring": [], 
  "public_key": "HPxXw3Kbkj8BVvgR49xa7jaUkHpmmqwL39pmk5qpbdjQ", 
  "software": "BigchainDB", 
  "version": "1.0.1"
}

BigchainDB Python Driver Hit from the client side.

Installation

pip3 install bigchaindb_driver
or
pip install bigchaindb_driver

Asset Creation & Transfer Asset Creation & Transfer

Since assets have an asset-like meaning, is data an image of assets? I'm sleepy. The bike belongs to Alice and assumes the process to be passed to Bob. The interpretation of the process is described in the comment.

python


# -*- coding: utf-8 -*-
from bigchaindb_driver import BigchainDB
from bigchaindb_driver.crypto import generate_keypair
from time import sleep
from sys import exit

#Cryptographic pair generation
alice, bob = generate_keypair(), generate_keypair()

bdb_root_url = 'http://0.0.0.0:9984'  #Rewrite to BigchainDB Root URL! !!

bdb = BigchainDB(bdb_root_url)

#Asset definition
bicycle_asset = {
    'data': {
        'bicycle': {
            'serial_number': 'abcd1234',
            'manufacturer': 'bkfab'
        },
    },
}
#You can optionally add metadata to the transaction
bicycle_asset_metadata = {
    'planet': 'earth'
}

#Asset Creation
#Instead of RDB records, bigchain stores data in transaction units.
#Preparing for transaction.
prepared_creation_tx = bdb.transactions.prepare(
    operation='CREATE',
    signers=alice.public_key,
    asset=bicycle_asset,
    metadata=bicycle_asset_metadata
)

#The transaction must be accomplished by signing with Alice's private key.
fulfilled_creation_tx = bdb.transactions.fulfill(
    prepared_creation_tx,
    private_keys=alice.private_key
)

#Send to BigchainDB node! !! !!
sent_creation_tx = bdb.transactions.send(fulfilled_creation_tx)

txid = fulfilled_creation_tx['id']

#Keep checking the transaction status until the transaction is valid
trials = 0
while trials < 60:
    try:
        if bdb.transactions.status(txid).get('status') == 'valid':
            print('Tx valid in:', trials, 'secs')
            break
    except bigchaindb_driver.exceptions.NotFoundError:
        trials += 1
        sleep(1)

if trials == 60:
    print('Tx is still being processed... Bye!')
    exit(0)

asset_id = txid

transfer_asset = {
    'id': asset_id
}

output_index = 0
output = fulfilled_creation_tx['outputs'][output_index]

transfer_input = {
    'fulfillment': output['condition']['details'],
    'fulfills': {
        'output_index': output_index,
        'transaction_id': fulfilled_creation_tx['id']
    },
    'owners_before': output['public_keys']
}

#Asset creation
prepared_transfer_tx = bdb.transactions.prepare(
    operation='TRANSFER',
    asset=transfer_asset,
    inputs=transfer_input,
    recipients=bob.public_key,
)

fulfilled_transfer_tx = bdb.transactions.fulfill(
    prepared_transfer_tx,
    private_keys=alice.private_key,
)

sent_transfer_tx = bdb.transactions.send(fulfilled_transfer_tx)

print("Is Bob the owner?",
    sent_transfer_tx['outputs'][0]['public_keys'][0] == bob.public_key)

print("Was Alice the previous owner?",
    fulfilled_transfer_tx['inputs'][0]['owners_before'][0] == alice.public_key)


The bike is under bob. The previous owner is alice. I saw the result.

Tx valid in: 0 secs
Is Bob the owner? True
Was Alice the previous owner? True

The outline is prepared, fulfilled and sent.

Library Reference

BigchainDB driver class

bigchaindb_driver.driver.TransactionsEndpoint

Executes the specified transaction.

Return value: fulfilled transaction payload dict ready to be sent to BigchainDB federation

Prepare for transaction payload preparation and fulfilled. You can select CREATE or TRANSFER in operation.

Return value: dict of prepared transaction

Submit a transaction to the federation.

Return value: dict of the transaction sent to the federation node

There are others, but details are below https://docs.bigchaindb.com/projects/py-driver/en/latest/libref.html?highlight=prepare#driver

Finally

The next time I write an article, I plan to dig a little deeper into the transfer of transactions and around the api.

ps

The node version was also docker and the demo worked perfectly. https://github.com/bigchaindb/bigchaindb-examples

Recommended Posts

Experience blockchain with BigchainDB
Blockchain tampering detection with Python
Implement blockchain with about 60 lines
Build a blockchain with Python ① Create a class
Experience Linux speeding up with Page cache
Single pixel camera to experience with Python