学习和理解区块链一个比较好的方法是自己动手写一个,代码的运行环境是python3.6,web框架用的是Flask,环境配置代码如下:1
2
3pip install pyOpenSSL
pip install flask
pip install requests
环境配置好之后,编码实现,直接上代码,建议大家读代码来理解,代码很少,比较简单,主要关注区块链之中的大概功能模块和使用流程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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286#!/usr/bin/env python
#encoding:utf-8
from flask import Flask, jsonify, request
import hashlib
import json
import os
import requests
import sys
from textwrap import dedent
from time import time
from urllib.parse import urlparse
from uuid import uuid4
class Blockchain(object):
def __init__(self):
self.chain = []
self.current_transactions = []
self.nodes = set()
# create the genesis block
self.new_block(proof=100, previous_hash=1)
def register_node(self, address):
"""
add a new node to the list of nodes
:param address: <str> address of the new node. Eg. 'http://localhost:3000'
:return: None
"""
parsed_url = urlparse(address)
self.nodes.add(parsed_url.netloc)
#pass
def valid_chain(self, chain):
"""
determine if a given blockchain is valid
:param chain: <list> a blockchain
:return: <bool> True if valid, False if not
"""
last_block = chain[0]
current_index = 1
while current_index < len(chain):
block = chain[current_index]
print(f'{last_block}')
print(f'{block}')
print("\n---------------\n")
# check that the hash of the block is correct or not
if block['previous_hash'] != self.hash(last_block):
return False
# check that the proof of work is correct
if not self.valid_proof(last_block['proof'], block['proof']):
return False
last_block = block
current_index += 1
return True
def resolve_conflicts(self):
"""
this is our confilct algorithm, it resolve the conflicts by replacing our chain with the longest one in the network
"return: <bool>, True if our chain was replaced, False if not
"""
neighbours = self.nodes
new_chain = None
# we are only looking for the longer chains than ours
max_length = len(self.chain)
for node in neighbours:
response = requests.get(f'http://{node}/chain')
if response.status_code == 200:
length = response.json()['length']
chain = response.json()['chain']
# check if the length is longer and the chain is valid
if length > max_length and self.valid_chain(chain):
max_length = length
new_chain = chain
# replace our chain if we discovered a new, longer and valid chain
if new_chain:
self.chain = new_chain
return True
return False
def new_block(self, proof, previous_hash=None):
# creates a new block and adds it to the chain
'''
create new block in the blockchain
:param proof: <int>the proof given by the Proof of work algorithm
:param previous_hash: (optional) <str> hash of previous block
:return: <dict> new block
'''
block = {
'index': len(self.chain) + 1,
'timestamp': time(),
'transactions': self.current_transactions,
'proof': proof,
'previous_hash': previous_hash or self.hash(self.chain[-1])
}
# reset the current list transactions
self.current_transactions = []
self.chain.append(block)
return block
#pass
def new_transaction(self, sender, recipient, amount):
# adds a new transaction to the list of the transactions
'''
create a new transaction to go into next mined block
:param sender: <Str> address of the sender
:param recipient: <Str> address of the recipient
:param amount: <Int> amount
:return: <Int> the index of the block that will hold the transaction
'''
self.current_transactions.append({
"sender": sender,
"recipient": recipient,
"amount": amount,
})
return self.last_block['index'] + 1
#pass
@staticmethod
def hash(block):
# hashes a block
'''
create a sha-256 hash of a block
:param block: <dict> block
:return: <str>
'''
# we must make sure theat he dictionary is ordered, or we'll have inconsistent hashes
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
#pass
@property
def last_block(self):
# return the last block in the chain
return self.chain[-1]
#pass
def proof_of_work(self, last_proof):
"""
simple proof of work algorithm
-find a number p', such that hash(pp') contains leading 4 zeros, where p is the privious p'
-p is the previous proof, and p' is the new proof
:param last_proof: <int>
:return: <int>
"""
proof = 0
while self.valid_proof(last_proof, proof) is False:
proof += 1
return proof
#pass
@staticmethod
def valid_proof(last_proof, proof):
"""
validates the proof: does hash(last_proof, proof) contain 4 leading zeros?
:param last_proof: <int> previous proof
:param proof: <int> current proof
:return: <bool> True if correct, False if not
"""
guess = f'{last_proof}{proof}'.encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:4] == "0000"
# Instantiate our node
app = Flask(__name__)
# Generate a global unique address of this node
node_identifier = str(uuid4()).replace('-', '')
# instantiate the blockchain
blockchain = Blockchain()
@app.route('/mine', methods=['GET'])
def mine():
#return 'we will mine a block'
# we run the proof of work algorithm to get the next proof
last_block = blockchain.last_block
last_proof = last_block['proof']
proof = blockchain.proof_of_work(last_proof)
# we must reward the miner a new block for finding the proof of work
# the sender is "0" to signify that this node has mined a new block
blockchain.new_transaction(sender="0", recipient=node_identifier, amount=1)
# forge the new block by adding it to the blockchain
previous_hash = blockchain.hash(last_block)
block = blockchain.new_block(proof, previous_hash)
response = {
'message': 'new block forged',
'index': block['index'],
'transactions': block['transactions'],
'proof': block['proof'],
'previous_hash': block['previous_hash'],
}
return jsonify(response), 200
@app.route('/transactions/new', methods=['POST'])
def new_transaction():
# return 'we will add a new transaction'
values = request.get_json()
# check that the required fields are in the post data
required = ['sender', 'recipient', 'amount']
if not all(k in values for k in required):
return 'Missing value', 400
# create a new transaction
index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])
response = {'message': f'transaction will be add to blockchain {index}'}
return jsonify(response), 201
@app.route('/chain', methods=['GET'])
def full_chain():
response = {
'chain':blockchain.chain,
'length':len(blockchain.chain),
}
return jsonify(response), 200
@app.route('/nodes/register', methods=['POST'])
def register_nodes():
values = request.get_json()
nodes = values.get('nodes')
if nodes is None:
return 'Error, please supply a valid list of nodes', 400
for node in nodes:
blockchain.register_node(node)
response = {
'message': 'new nodes have been added',
'total_nodes': list(blockchain.nodes),
}
return jsonify(response), 201
@app.route('/nodes/resolve', methods=['GET'])
def consensus():
replaced = blockchain.resolve_conflicts()
if replaced:
response = {
'message': 'our chain has been relplaced',
'new_chain': blockchain.chain,
}
else:
response = {
'message': 'our chain is authoritative',
'new_chain': blockchain.chain,
}
return jsonify(response), 200
if __name__ == '__main__':
port = int(sys.argv[1])
#print(f'{port}')
app.run(host='0.0.0.0', port=port)
在其中一个窗口启动区块链1
python blockchain.py 3000
在另外一个窗口访问,从返回结果中可以观察区块链中内容的变化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#查看当前区块链详细信息
curl "http://localhost:3000/chain"
{"chain":[{"index":1,"previous_hash":1,"proof":100,"timestamp":1536296820.6712275,"transactions":[]}],"length":1}
#挖矿
curl "http://localhost:3000/mine"
{"index":2,"message":"new block forged","previous_hash":"8c90381887446fa7ef00e8ff4fa3820c67271caee9250a7311e64b5fd9ca5fba","proof":35293,"transactions":[{"amount":1,"recipient":"f4eb4686d2314f7b926472390af4a8d8","sender":"0"}]}
#查看当前区块链详细信息
curl "http://localhost:3000/chain"
{"chain":[{"index":1,"previous_hash":1,"proof":100,"timestamp":1536296820.6712275,"transactions":[]},{"index":2,"previous_hash":"8c90381887446fa7ef00e8ff4fa3820c67271caee9250a7311e64b5fd9ca5fba","proof":35293,"timestamp":1536296905.7136853,"transactions":[{"amount":1,"recipient":"f4eb4686d2314f7b926472390af4a8d8","sender":"0"}]}],"length":2}
#产生新的交易
curl -X POST -H "Content-Type: application/json" -d '{ "sender":"0", "recipient": "f4eb4686d2314f7b926472390af4a8d8", "amount": 5}' "http://localhost:3000/transactions/new"
{"message":"transaction will be add to blockchain 3"}
#查看当前区块链详细信息
{"chain":[{"index":1,"previous_hash":1,"proof":100,"timestamp":1536296820.6712275,"transactions":[]},{"index":2,"previous_hash":"8c90381887446fa7ef00e8ff4fa3820c67271caee9250a7311e64b5fd9ca5fba","proof":35293,"timestamp":1536296905.7136853,"transactions":[{"amount":1,"recipient":"f4eb4686d2314f7b926472390af4a8d8","sender":"0"}]}],"length":2}
#挖矿
curl "http://localhost:3000/mine"
{"index":3,"message":"new block forged","previous_hash":"b6ea6eaf341b0d54a441d96487c1b6c939ed24152f1e3edb13f321d429be9c9a","proof":35089,"transactions":[{"amount":5,"recipient":"f4eb4686d2314f7b926472390af4a8d8","sender":"0"},{"amount":1,"recipient":"f4eb4686d2314f7b926472390af4a8d8","sender":"0"}]}
#查看当前区块链详细信息
{"chain":[{"index":1,"previous_hash":1,"proof":100,"timestamp":1536296820.6712275,"transactions":[]},{"index":2,"previous_hash":"8c90381887446fa7ef00e8ff4fa3820c67271caee9250a7311e64b5fd9ca5fba","proof":35293,"timestamp":1536296905.7136853,"transactions":[{"amount":1,"recipient":"f4eb4686d2314f7b926472390af4a8d8","sender":"0"}]},{"index":3,"previous_hash":"b6ea6eaf341b0d54a441d96487c1b6c939ed24152f1e3edb13f321d429be9c9a","proof":35089,"timestamp":1536297373.46994,"transactions":[{"amount":5,"recipient":"f4eb4686d2314f7b926472390af4a8d8","sender":"0"},{"amount":1,"recipient":"f4eb4686d2314f7b926472390af4a8d8","sender":"0"}]}],"length":3}
另启动一个窗口,增加一个运行节点,端口30011
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
29python blockchain.py 3001
#并将节点连接入区块链
curl -X POST -H "Content-Type: application/json" -d '{ "nodes": ["http://localhost:3001/"] }' "http://localhost:3000/nodes/register"
{"message":"new nodes have been added","total_nodes":["localhost:3001"]}
#查看当前区块链详细信息
curl "http://localhost:3001/chain"
{"chain":[{"index":1,"previous_hash":1,"proof":100,"timestamp":1536297764.5623543,"transactions":[]}],"length":1}
#同步和解决冲突,目前3000下面的链应该是最长的,所以同步后还是自身
curl "http://localhost:3000/nodes/resolve"
{"message":"our chain is authoritative","new_chain":[{"index":1,"previous_hash":1,"proof":100,"timestamp":1536296820.6712275,"transactions":[]},{"index":2,"previous_hash":"8c90381887446fa7ef00e8ff4fa3820c67271caee9250a7311e64b5fd9ca5fba","proof":35293,"timestamp":1536296905.7136853,"transactions":[{"amount":1,"recipient":"f4eb4686d2314f7b926472390af4a8d8","sender":"0"}]},{"index":3,"previous_hash":"b6ea6eaf341b0d54a441d96487c1b6c939ed24152f1e3edb13f321d429be9c9a","proof":35089,"timestamp":1536297373.46994,"transactions":[{"amount":5,"recipient":"f4eb4686d2314f7b926472390af4a8d8","sender":"0"},{"amount":1,"recipient":"f4eb4686d2314f7b926472390af4a8d8","sender":"0"}]}]}
#通过对3001节点挖矿4次,使之成为最长的链
curl "http://localhost:3001/mine"
{"index":2,"message":"new block forged","previous_hash":"014e9b638a7e9f15967bfbda1f697be93a5a8ce8f95f29b37bdd6d9e75d4bb19","proof":35293,"transactions":[{"amount":1,"recipient":"1f5fc2bb534249508697f8d7b090e5f1","sender":"0"}]}
curl "http://localhost:3001/mine"
{"index":3,"message":"new block forged","previous_hash":"1b7a90c1d7b1dbb9cab708035d3b22d25bc398e2688efa7171a942ff22a81740","proof":35089,"transactions":[{"amount":1,"recipient":"1f5fc2bb534249508697f8d7b090e5f1","sender":"0"}]}
curl "http://localhost:3001/mine"
{"index":4,"message":"new block forged","previous_hash":"ca5affcd2926f6209b8a35ff2a78fc52ec0c2b153f9b7ccea997726dbf5d6a03","proof":119678,"transactions":[{"amount":1,"recipient":"1f5fc2bb534249508697f8d7b090e5f1","sender":"0"}]}
curl "http://localhost:3001/mine"
{"index":5,"message":"new block forged","previous_hash":"430eac2b191b2690dcc6a8400a63f638d41da80674b6aa8905e050c87232f2a5","proof":146502,"transactions":[{"amount":1,"recipient":"1f5fc2bb534249508697f8d7b090e5f1","sender":"0"}]}
curl "http://localhost:3001/chain"
{"chain":[{"index":1,"previous_hash":1,"proof":100,"timestamp":1536297764.5623543,"transactions":[]},{"index":2,"previous_hash":"014e9b638a7e9f15967bfbda1f697be93a5a8ce8f95f29b37bdd6d9e75d4bb19","proof":35293,"timestamp":1536298287.1541448,"transactions":[{"amount":1,"recipient":"1f5fc2bb534249508697f8d7b090e5f1","sender":"0"}]},{"index":3,"previous_hash":"1b7a90c1d7b1dbb9cab708035d3b22d25bc398e2688efa7171a942ff22a81740","proof":35089,"timestamp":1536298288.8839533,"transactions":[{"amount":1,"recipient":"1f5fc2bb534249508697f8d7b090e5f1","sender":"0"}]},{"index":4,"previous_hash":"ca5affcd2926f6209b8a35ff2a78fc52ec0c2b153f9b7ccea997726dbf5d6a03","proof":119678,"timestamp":1536298290.0008492,"transactions":[{"amount":1,"recipient":"1f5fc2bb534249508697f8d7b090e5f1","sender":"0"}]},{"index":5,"previous_hash":"430eac2b191b2690dcc6a8400a63f638d41da80674b6aa8905e050c87232f2a5","proof":146502,"timestamp":1536298291.5808423,"transactions":[{"amount":1,"recipient":"1f5fc2bb534249508697f8d7b090e5f1","sender":"0"}]}],"length":5}
#同步和解决冲突,目前3001下面的链应该是最长的,所以同步后,应该会被3001的链取代
curl "http://localhost:3000/nodes/resolve"
{"message":"our chain has been relplaced","new_chain":[{"index":1,"previous_hash":1,"proof":100,"timestamp":1536297764.5623543,"transactions":[]},{"index":2,"previous_hash":"014e9b638a7e9f15967bfbda1f697be93a5a8ce8f95f29b37bdd6d9e75d4bb19","proof":35293,"timestamp":1536298287.1541448,"transactions":[{"amount":1,"recipient":"1f5fc2bb534249508697f8d7b090e5f1","sender":"0"}]},{"index":3,"previous_hash":"1b7a90c1d7b1dbb9cab708035d3b22d25bc398e2688efa7171a942ff22a81740","proof":35089,"timestamp":1536298288.8839533,"transactions":[{"amount":1,"recipient":"1f5fc2bb534249508697f8d7b090e5f1","sender":"0"}]},{"index":4,"previous_hash":"ca5affcd2926f6209b8a35ff2a78fc52ec0c2b153f9b7ccea997726dbf5d6a03","proof":119678,"timestamp":1536298290.0008492,"transactions":[{"amount":1,"recipient":"1f5fc2bb534249508697f8d7b090e5f1","sender":"0"}]},{"index":5,"previous_hash":"430eac2b191b2690dcc6a8400a63f638d41da80674b6aa8905e050c87232f2a5","proof":146502,"timestamp":1536298291.5808423,"transactions":[{"amount":1,"recipient":"1f5fc2bb534249508697f8d7b090e5f1","sender":"0"}]}]}
上面是对区块链基本操作的简单理解实现,感兴趣的同学可以自行扩展,可以参考 https://hackernoon.com/learn-blockchains-by-building-one-117428612f46