Skip to content

Commit 4f6879e

Browse files
committed
Python BlockChain
1 parent c385ba1 commit 4f6879e

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

taiyangxue/README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,9 @@
1616
- [python39](https://github.com/JustDoPython/python-examples/tree/master/taiyangxue/python39) : 你在享受十一长假时,Python 已悄悄地变了
1717
- [matrix](https://github.com/JustDoPython/python-examples/tree/master/taiyangxue/matrix) : Python 世界的黑客帝国
1818
- [why](https://github.com/JustDoPython/python-examples/tree/master/taiyangxue/why) : 练那么多,为啥还不会编程
19-
- [rate](https://github.com/JustDoPython/python-examples/tree/master/taiyangxue/rate-of-return) : 练那么多,为啥还不会编程
19+
- [rate](https://github.com/JustDoPython/python-examples/tree/master/taiyangxue/rate-of-return) : 做时间的朋友,必须知道收益咋算
20+
- [blockchain](https://github.com/JustDoPython/python-examples/tree/master/taiyangxue/blockchain) : 比特币涨疯了,区块链是什么鬼?
21+
2022
---
2123

2224
从小白到工程师的学习之路

taiyangxue/blockchain/main.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import hashlib as hasher
2+
import datetime as date
3+
4+
class Block:
5+
def __init__(self, index, timestamp, data, previous_hash):
6+
self.index = index
7+
self.timestamp = timestamp
8+
self.data = data
9+
self.previous_hash = previous_hash
10+
self.hash = self.hash_block()
11+
12+
def hash_block(self):
13+
sha = hasher.sha256()
14+
sha.update((str(self.index) + str(self.timestamp) + str(self.data) + str(self.previous_hash)).encode("utf-8"))
15+
return sha.hexdigest()
16+
17+
def create_genesis_block():
18+
# 手工创建第一个区块,其索引为 0,且随意取给紧前特征值 '0'
19+
return Block(0, date.datetime.now(), "Genesis Block", "0")
20+
21+
def next_block(last_block):
22+
this_index = last_block.index + 1
23+
this_timestamp = date.datetime.now()
24+
this_data = "Hey! I'm block " + str(this_index)
25+
this_hash = last_block.hash
26+
return Block(this_index, this_timestamp, this_data, this_hash)
27+
28+
# 创建一个区块链,并将第一个区块加入
29+
blockchain = [create_genesis_block()]
30+
31+
# 设置产生区块的个数
32+
num_of_blocks_to_add = 20
33+
34+
# 产生区块并加入区块链
35+
for i in range(0, num_of_blocks_to_add):
36+
previous_block = blockchain[-1]
37+
block_to_add = next_block(previous_block)
38+
blockchain.append(block_to_add)
39+
# 发布当前区块的信息
40+
print("Block #{} has been added to the blockchain!".format(block_to_add.index))
41+
print("Hash: {}\n".format(block_to_add.hash))

0 commit comments

Comments
 (0)