区块链的特性
- 去中心化
- 防篡改(这里就利用了这特性)
原理
目的
利用的区块链的防串改特性
整合
在原来的数据库表结构基础上新增 previous_hash, hash字段。
hash是由index, timestamp, data等字段经过sha256 算法之后的hash
防串改的原理
每条记录带上上一条的hash,当前的hash, 如果当前字段的修改了,当前的hash不一样,存储在下一条的hash也会不一样,这样就达到了验证的目的。
说白了,就是利用两点:
1.各字段组合hash
2.每条记录带着上一条记录的凭证
代码
import hashlib
import datetime
class Block:
def __init__(self, index, timestamp, data, previos_hash):
self.index = index
self.timestamp = timestamp
self.data = data
self.previous_hash = previos_hash
self.hash = self.hash_block()
def hash_block(self):
sha = hashlib.sha256()
hash_value = "{}{}{}{}".format(self.index, self.timestamp, self.data, self.previous_hash)
sha.update(hash_value.encode("utf-8"))
return sha.hexdigest()
def create_genesis_block():
return Block(0, datetime.datetime.now(), "Genesis Block", "0")
def next_block(last_block):
this_index = last_block.index + 1
this_timestamp = datetime.datetime.now()
this_data = "Hey! i am block" + str(this_index)
this_hash = last_block.hash
return Block(this_index, this_timestamp, this_data, this_hash)
blockchain = [create_genesis_block()]
previous_block = blockchain[0]
for i in range(0, 20):
previous_block = blockchain[i]
block_to_add = next_block(previous_block)
blockchain.append(block_to_add)
print("Block #{} has been added to the blockchain!".format(block_to_add.index))
print("Hash: {}\n".format(block_to_add.hash))