目录
前言
本篇文章将从一个实践者的角度出发,通过构建一个简单的区块链系统,揭开区块链技术的神秘面纱。我们将使用Python语言,结合Flask框架,创建一个可以处理交易、挖矿新区块、验证区块链有效性,并能在网络节点间同步的区块链网络。。
一、代码展示
# Module 1 -Create a Cryptocurrency
#To be installed:
#Flask==0.12.2:pip install Flask==0.12.2
#Postman HTrp Client:https://www.getpostman.com
#requests==2.18.4:pip install requests=-2.18.4
#时间戳
import datetime
import hashlib
import json
#Flask可以定义Web应用的路由(URL到Python函数的映射),并处理HTTP请求和响应。jsonify是一个函数,用于将Python对象转换为JSON格式的响应。当你在Flask路由函数中返回一个jsonify对象时,Flask会自动将该对象对应的数据转换为JSON格式,并设置合适的HTTP响应头,以便客户端可以正确解析响应内容。
from flask import Flask, jsonify,request
import requests
from uuid import uuid4
from urllib.parse import urlparse
# 1******Building a Blockchain
class Blockchain:
def __init__(self):
self.transactions=[]
self.chain=[]
self.create_block(proof=1,previous_hash='0')
self.nodes=set()
def create_block(self,proof,previous_hash):
block={'index':len(self.chain)+1,
'timestamp':str(datetime.datetime.now()),
'proof':proof,
'previous_hash':previous_hash,
'transactions':self.transactions}
self.transactions=[]
self.chain.append(block)
return block
def get_previous_block(self):
return self.chain[-1]
def proof_of_work(self,previous_proof):
new_proof=1
check_proof=False
while check_proof is False:
hash_oparation=hashlib.sha256(str(new_proof**2-previous_proof**2).encode()).hexdigest()
if hash_oparation[:4]=='0000':
check_proof=True
else:
new_proof+=1
return new_proof
def hash(self, block):
encode_block = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(encode_block).hexdigest()
def is_chain_valid(self,chain):
previous_block=chain[0]
block_index=1
while block_index<len(chain):
block=chain[block_index]
if block['previous_hash'] !=self.hash(previous_block):
return False
previous_proof=previous_block['proof']
proof=block['proof']
hash_oparation=hashlib.sha256(str(proof**2-previous_proo

最低0.47元/天 解锁文章
216

被折叠的 条评论
为什么被折叠?



