The ground is the bed. The sky is the meteor is the tears.
Sometimes awake, sometimes drunk, geese fly back and forth

I heard that the wages of the blockchain technology are now high, and with the illusion of high wages, I decided to start learning the blockchain. Then the first step I want to touch the blockchain must be to register an account with the trading platform, and then add some money to buy 0.00001 BTC. (2333,~!~ Now I am so poor that only the coins are left)

To be honest, the blockchain technology is still a bit difficult to understand. For this reason, I searched the implementation code of the blockchain. I thought it would be simpler to combine the code, so I found that someone implemented a simple blockchain in python. So on the basis of the original author, I slightly modified the content, paste it here for learning. Original project address: https://github.com/xilibi2003/blockchain

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
#! -*- coding:utf-8 -*-
import hashlib
import json
from time import time
class Blockchain(object):
''' blockchain
A block structure (the lexicographic order of each block must be the same):
block = {
'index': 1, #block index
'timestamp': 1506057125.900785, # timestamp
{
'sender': "8527147fe1f5426f9dd545de4b27ee00",
'recipient': "a77f5cdfa2934df3954a5c7c7da5df1f",
'amount': 5,
}
],
'proof': 324984774000, # proof of workload
'previous_hash': "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
}
'''
def __init__(self):
Self.chain = [] # block list
Self.current_transactions = [] # transaction list
Self.nodes = set() # node list (avoid duplicates)
Self.new_block(previous_hash=1, proof=100) # Create a creation block
def register_node(self,address):
''' Register node
Add a new node to the list of nodes
:param address: <str> Node address '192.168.0.1:5000'
:return: None
'''
self.nodes.add(address)
def valid_chain(self,chain):
''' Verify the validity of the blockchain
:param chain: <list> A complete blockchain
:return: <bool> True if valid, False if not
'''
Previous_block = chain[0] # previous block
Current_index = 1 # current block index
while current_index < len(chain):
Block = chain[current_index] # current block
if block['previous_hash'] != self.hash(previous_block):
''' hash value verification '''
return False
if not self.valid_proof(previous_block['proof'],block['proof']):
''' Workload proof verification '''
return False
previous_block = block
current_index += 1
return True
def resolve_conflicts(self):
''' Consensus algorithm solves conflicts between different node books
Use the longest active blockchain in the network
:return: <bool> True if the chain is replaced, otherwise False
'''
Neighbors = self.nodes # list of all nodes in the network
new_chain = None
Max_length = len(self.chain) # blockchain length of the current node
For node in neighbours: # traverse all network nodes, if there is a longer chain than the active block of this node, replace the local blockchain
#Get through api
Length = 100 # block node length
Chain = [] # a node blockchain list
if length > max_length and self.valid_chain(chain):
max_length = length
new_chain = chain
if new_chain:
self.chain = new_chain
return True
return False
def new_block(self,proof,previous_hash=None):
''' Create a new block and add it to the blockchain
Generate new blocks
:param proof: <int> proof of workload
:param previous_hash: hash value of the previous block
:return: <dict> new block
'''
block = {
'index': len(self.chain) + 1, # Make sure the index is at the end of the blockchain
'timestamp': time(),
'transactions': self.current_transactions, # transaction list
'proof': proof, # proof of workload
'previous_hash': previous_hash or self.hash(self.chain[-1]), # hash of the previous block of this block
}
# You can operate on the details of the transaction, such as adding gold coins, or reducing coins.
Self.current_transactions = [] # Reset transaction list
Self.chain.append(block) # Add new blocks to the blockchain
return block
def new_transactions(self,sender,recipient,amount):
''' Add a new transaction to the list of transactions
Generate new transaction information, the information will be added to the next block to be dug
:param sender: <str> sender address
:param recipient: <str> Receive address
:param amount: <int> Amount or quantity
:return: <int> Returns the blockchain index of this transaction (add this transaction to the end of the blockchain)
'''
self.current_transactions.append({
"Transmitter": transmitter,
'recipient':recipient,
'amount':amount,
})
return self.last_block['index'] + 1
@staticmethod
def hash(block):
''' Calculate the hash value of a block
Generate the SHA-256 hash value of the block
:param block: <dict> Block
:return: <str>
'''
block_string = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(block_string).hexdigest()
@property
def last_block(self):
''' The last block in the blockchain '''
Return self.chain[-1] # returns the last block in the blockchain
def proof_of_work(self, last_proof):
'''
Simple workload proof:
- Find a p' such that hash(pp') starts with 4 zeros
- p is proof of the previous block, p' is the current proof
:param last_proof: <int>
:return: <int>
'''
proof = 0
while self.valid_proof(last_proof, proof) is False:
proof += 1
return proof
@staticmethod
def valid_proof(last_proof,proof):
'''
Verification: Does hash (last_proof, proof) start with 4 zeros?
:param last_proof: <int> hash of the previous block
:param proof: <int> the hash of the current block
:return: <bool> True or False
'''
guess = (str(last_proof)+str(proof)).encode()
guess_hash = hashlib.sha256(guess).hexdigest()
return guess_hash[:4] == "0000"
if __name__=="__main__":
# Running this script is a blockchain node, and nodes can pass information to each other through api.
# Each node runs every 10 minutes
blockchain = Blockchain ()
for i in range(2):
#Sync the block
#Start mining
last_block = blockchain.last_block
last_proof = last_block['proof']
proof = blockchain.proof_of_work(last_proof)
# After the mining is successful, generate a new transaction (reward transaction)
blockchain.new_transactions(sender="0",recipient="000002",amount=1)
# Add a new transaction (not a reward transaction, but a normal transaction)
blockchain.new_transactions(sender="0000001",recipient="000002",amount=1)
# Output current transaction list
print "current_transactions lists is: \n",blockchain.current_transactions
# After successful mining, a new block (including bonus transaction information and new transaction information) will be generated. Only after successful mining can a new block be created.
block = blockchain.new_block(proof)
# Output current blockchain
print "current chain lists is: \n",blockchain.chain

From the beginning of this article, I will continue to learn some blockchain technology and blockchain security related technologies, and will summarize into a series of articles published in the blog, technical support, please bear with me!

本文标题:

文章作者:nmask

发布时间:2018年05月25日 - 15:05

最后更新:2019年08月16日 - 15:08

原始链接:https://thief.one/2018/05/25/1/en/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

nmask wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
坚持原创技术分享,您的支持将鼓励我继续创作!

热门文章推荐: