-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathblockchain_server.py
More file actions
93 lines (76 loc) · 2.69 KB
/
blockchain_server.py
File metadata and controls
93 lines (76 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
from flask import Flask
from flask import jsonify
from flask import request
import blockchain
import wallet
app = Flask(__name__)
cache = {}
def get_blockchain():
cached_blockchain = cache.get('blockchain')
if not cached_blockchain:
miners_wallet = wallet.Wallet()
cache['blockchain'] = blockchain.BlockChain(
blockchain_address=miners_wallet.blockchain_address,
port=app.config['port'])
app.logger.warning({
'private_key': miners_wallet.private_key,
'public_key': miners_wallet.public_key,
'blockchain_address': miners_wallet.blockchain_address})
return cache['blockchain']
@app.route('/chain', methods=['GET'])
def get_chain():
block_chain = get_blockchain()
response = {
'chain': block_chain.chain
}
return jsonify(response), 200
@app.route('/transactions', methods=['GET', 'POST'])
def transaction():
block_chain = get_blockchain()
if request.method == 'GET':
transactions = block_chain.transaction_pool
response = {
'transactions': transactions,
'length': len(transactions)
}
return jsonify(response), 200
if request.method == 'POST':
request_json = request.json
required = (
'sender_blockchain_address',
'recipient_blockchain_address',
'value',
'sender_public_key',
'signature')
if not all(k in request_json for k in required):
return jsonify({'message': 'missing values'}), 400
is_created = block_chain.create_transaction(
request_json['sender_blockchain_address'],
request_json['recipient_blockchain_address'],
request_json['value'],
request_json['sender_public_key'],
request_json['signature'],
)
if not is_created:
return jsonify({'message': 'fail'}), 400
return jsonify({'message': 'success'}), 201
@app.route('/mine', methods=['GET'])
def mine():
block_chain = get_blockchain()
is_mined = block_chain.mining()
if is_mined:
return jsonify({'message': 'success'}), 200
return jsonify({'message': 'fail'}), 400
@app.route('/mine/start', methods=['GET'])
def start_mine():
get_blockchain().start_mining()
return jsonify({'message': 'success'}), 200
if __name__ == '__main__':
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-p', '--port', default=5000,
type=int, help='port to listen on')
args = parser.parse_args()
port = args.port
app.config['port'] = port
app.run(host='0.0.0.0', port=port, threaded=True, debug=True)