├── LICENSE.md ├── nouce.py ├── hash.py ├── README.md └── main.py /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Adam K.C. Chin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /nouce.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2017 Adam K.C. Chin 3 | # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 5 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 6 | 7 | from flask import Flask, request 8 | from flask_restful import Resource, Api 9 | from json import dumps 10 | from flask.ext.jsonpify import jsonify 11 | 12 | 13 | import random 14 | 15 | app = Flask(__name__) 16 | api = Api(app) 17 | 18 | 19 | 20 | class nouce(Resource): 21 | def get(self): 22 | nouce = "%032x" % random.getrandbits(256) 23 | randomv = {'nouce': nouce} 24 | return jsonify(randomv); 25 | 26 | 27 | api.add_resource(nouce, '/nouce') 28 | 29 | if __name__ == "__main__": 30 | app.run(host='127.0.0.1', port='8001') 31 | -------------------------------------------------------------------------------- /hash.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2017 Adam K.C. Chin 3 | # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 5 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 6 | 7 | from flask import Flask, request 8 | from flask_restful import Resource, Api 9 | from json import dumps, loads 10 | from flask_jsonpify import jsonpify 11 | 12 | from hashlib import sha256 13 | 14 | app = Flask(__name__) 15 | 16 | 17 | @app.route("/hash/", methods = ['GET', 'POST']) 18 | def hash(): 19 | if request.method == 'POST': 20 | data = request.form['data'] 21 | data_sha256 = sha256(dumps(loads(data), sort_keys=True).encode('utf-8')).hexdigest() 22 | hashjson = {'hash': data_sha256} 23 | return jsonpify(hashjson) 24 | else: 25 | return ' ' 26 | 27 | if __name__ == "__main__": 28 | app.run(host='127.0.0.1', port='8002') 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Blockchain Database API 2 | Thin Database Architecture based on Blockchain technology 3 | 4 | ![](https://cdn-images-1.medium.com/max/720/1*ZUA06XdNnJ7oDh_zLTFm-w.png) 5 | 6 | Background 7 | --------------------------------------------- 8 | When we talk about Blockchain, we always relate it to peer-to-peer network and think that data must be distributed across the network. It will raise concern from people and think that Blockchain would breach the confidentiality of the data. 9 | 10 | Actually, the data architecture of Blockchain itself already provides a good solution for securing the data from unauthorized manipulation, given that the server is protected by sufficient controls, such as access control, network and system security control, and better to be in an internal network.  11 | 12 | Therefore, I try to build an database based on the data architecture of Blockchain by using Python, Sqlite and RESTful API framework. 13 | 14 | Objective 15 | --------------------------------------------- 16 | **Accountability, Confidentially and Integrity** 17 | 18 | When the user create a transaction record, he encrypts the data with its private key and post the data to Blockchain Database API. Blockchain Database API will decrypt the data with the user’s public key. In this process, the user’s identity has been confirmed. It achieves the objective of accountability and confidentially. 19 | 20 | In the next step, Blockchain Database API will calculate the hash value for the transaction with nonce, i.e. random string, and the previous hash. Blockchain Database API will insert the transaction, nonce and hash to the database.  21 | 22 | To detect any unauthorized change, Blockchain Database API will re-calculate the hash value based on the information of the previous hash, transaction and nonce. If any change is made, the hash value will change and the API can be notified. Therefore, the integrity of the data will be ensured.  23 | 24 | How to use? 25 | -------------------------------------------- 26 | 1. Start the Hash API 27 | 28 | ```python 29 | python hash.py 30 | ``` 31 | 32 | 2. Start the Nonce API 33 | 34 | ```python 35 | python nonce.py 36 | ``` 37 | 38 | 3. Start the Main API 39 | 40 | ```python 41 | python main.py 42 | ``` 43 | 44 | 4. Post the Journal Data to Main API http://127.0.0.1:8000/construct and Get back the Response with nonce and hash 45 | 46 | ```json 47 | data1 = { "journal_id": "JE000001", 48 | "entry_date" : "2016-11-06", 49 | "create_time" : "2016-11-06 18:00:00", 50 | "created_by": "Adam", 51 | "post_status": "P", 52 | "account_code" : "100000", 53 | "amount" : 16453.24, 54 | "dr_cr" : "C" 55 | 56 | } 57 | ``` 58 | 59 | 5. Post the Response to Main API http://127.0.0.1:8000/insert 60 | 61 | ```json 62 | data1 = { "journal_id": "JE000001", 63 | "entry_date" : "2016-11-06", 64 | "create_time" : "2016-11-06 18:00:00", 65 | "created_by": "Adam", 66 | "post_status": "P", 67 | "account_code" : "100000", 68 | "amount" : 16453.24, 69 | "dr_cr" : "C", 70 | "nonue" : ".....", 71 | "hash" : "....." 72 | } 73 | ``` 74 | 75 | 6. Verify your transaction by Get http://127.0.0.1:8000/verify?id=1 76 | 77 | Limitation 78 | --------------------------------------------- 79 | Since it is in a centralized architecture, there is a possibility for the attacker, who obtains the administration right, to change the entire database by recalculating the hash value again.  80 | This can be safeguarded by the following solutions: 81 | - Clone the transaction to a secured log server   82 | - Back up the data incrementally (line by line transaction) rather than full backup 83 | 84 | 85 | 86 | License 87 | ---------------------------------------------- 88 | MIT License 89 | 90 | Copyright (c) 2017 Adam K.C. Chin 91 | 92 | Permission is hereby granted, free of charge, to any person obtaining a copy 93 | of this software and associated documentation files (the "Software"), to deal 94 | in the Software without restriction, including without limitation the rights 95 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 96 | copies of the Software, and to permit persons to whom the Software is 97 | furnished to do so, subject to the following conditions: 98 | 99 | The above copyright notice and this permission notice shall be included in all 100 | copies or substantial portions of the Software. 101 | 102 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 103 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 104 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 105 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 106 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 107 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 108 | SOFTWARE. 109 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | # MIT License 2 | # Copyright (c) 2017 Adam K.C. Chin 3 | # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 5 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 6 | 7 | import sqlite3 8 | from flask import Flask, request 9 | from flask_restful import Resource, Api 10 | from json import dumps, loads 11 | from flask_jsonpify import jsonpify 12 | import json 13 | import requests 14 | 15 | 16 | def call_hash(data): 17 | url = 'http://127.0.0.1:8002/hash/' 18 | try: 19 | del data['hash'] 20 | except: 21 | pass 22 | data2={} 23 | data2['data']=json.dumps(data) 24 | #print data2 25 | response = requests.post(url, data=data2, allow_redirects=False) 26 | if response.status_code == 200: 27 | return response.json()['hash'] 28 | 29 | def call_nouce(): 30 | nouce_url = 'http://127.0.0.1:8001/nouce' 31 | response = requests.get(nouce_url) 32 | if response.status_code == 200: 33 | return response.json()['nouce'] 34 | 35 | 36 | def get_pre_hash(cursor): 37 | cursor.execute('select * from journal order by id desc limit 1') 38 | results = cursor.fetchall() 39 | if results: 40 | return results[0]['hash'] 41 | else: 42 | return "" 43 | 44 | 45 | def database_connect(): 46 | conn = sqlite3.connect('blockchain.db') 47 | conn.row_factory = dict_factory 48 | cursor = conn.cursor() 49 | return conn, cursor 50 | 51 | 52 | def data_contruct_new(data1): 53 | nouce = {"nouce":u""} 54 | hash = {"hash":u""} 55 | pre_hash = {"pre_hash":u""} 56 | data1.update(nouce) 57 | data1.update(hash) 58 | data1.update(pre_hash) 59 | return data1 60 | 61 | def dict_factory(cursor, row): 62 | d = {} 63 | for idx, col in enumerate(cursor.description): 64 | d[col[0]] = row[idx] 65 | return d 66 | 67 | app = Flask(__name__) 68 | 69 | 70 | 71 | 72 | @app.route("/insert", methods = ['GET', 'POST']) 73 | def insert(): 74 | if request.method == 'POST': 75 | data = request.form['data'] 76 | data1 = loads(data) 77 | conn, cursor = database_connect() 78 | try: 79 | cursor.execute("insert into journal(journal_id, entry_date, create_time, created_by, post_status, account_code, amount, dr_cr, nouce, hash) values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [ data1['journal_id'], data1['entry_date'], data1['create_time'], data1['created_by'], data1['post_status'], data1['account_code'], data1['amount'], data1['dr_cr'], data1['nouce'], data1['hash']]) 80 | conn.commit() 81 | return "Success" 82 | except: 83 | return "Failed" 84 | conn.close() 85 | else: 86 | return "" 87 | 88 | 89 | @app.route("/verify", methods = ['GET', 'POST']) 90 | def verify(): 91 | if request.method == 'GET': 92 | try: 93 | id = request.args.get('id', default = 2, type = int) 94 | conn, cursor = database_connect() 95 | cursor.execute('select * from journal where id <= ? order by id desc limit 2', [id,]) 96 | results = cursor.fetchall() 97 | records_verify = results[0] 98 | hash_now = results[0]['hash'] 99 | pre_hash = {u"pre_hash":u""} 100 | records_verify.update(pre_hash) 101 | records_verify['pre_hash'] = results[1]['hash'] 102 | del records_verify['id'] 103 | hash_value = call_hash(records_verify) 104 | conn.close() 105 | if hash_value == hash_now: 106 | return "Verified" 107 | else: 108 | return "Failed" 109 | except: 110 | return "Error" 111 | conn.close() 112 | else: 113 | return "" 114 | 115 | 116 | @app.route("/construct", methods = ['GET', 'POST']) 117 | def construct(): 118 | if request.method == 'POST': 119 | data = request.form['data'] 120 | data1 = loads(data) 121 | conn, cursor = database_connect() 122 | data1 = data_contruct_new(data1) 123 | data1['pre_hash'] = get_pre_hash(cursor) 124 | data1['nouce'] = call_nouce() 125 | data1['hash'] = call_hash(data1) 126 | conn.close() 127 | return jsonpify(data1) 128 | else: 129 | return "" 130 | 131 | 132 | if __name__ == "__main__": 133 | app.run(host='127.0.0.1', port='8000') 134 | --------------------------------------------------------------------------------