精华内容
下载资源
问答
  • 区块链 python

    2018-06-21 15:24:39
    初始区块链 特点:        区块链是由区块的记录构成的不可变,有序的链记录。主要有以下几个特点:        1:...

    初始区块链

    特点:

           区块链是由区块的记录构成的不可变,有序的链记录。主要有以下几个特点:
           1:去中心化
           由于使用分布式核算和存储,不存在中心化的硬件或管理机构,任意节点的权利和义务都是均等的,系统中的数据块由整个系统中具有维护功能的节点来共同维护。得益于区块链的去中心化特征,比特币也有去中心化的特征 。
           2:开放性
           系统是开放的,除了交易各方的私有信息被加密外,区块链的数据对所有人公开,任何人都可以通过公开的接口查询区块链数据和开发相关应用,因此整个系统信息高度透明。
           3:自治性
           区块链采用基于协商一致的规范和协议(比如一套公开透明的算法)使得整个系统中的所有节点能够在去信任的环境自由安全的交换数据,使得对“人”的信任改成了对机器的信任,任何人为的干预不起作用。
           4:信息不可篡改
           一旦信息经过验证并添加至区块链,就会永久的存储起来,除非能够同时控制住系统中超过51%的节点,否则单个节点上对数据库的修改是无效的,因此区块链的数据稳定性和可靠性极高。
           5:匿名性
           由于节点之间的交换遵循固定的算法,其数据交互是无需信任的(区块链中的程序规则会自行判断活动是否有效),因此交易对手无须通过公开身份的方式让对方对自己产生信任,对信用的累积非常有帮助。
    这里写图片描述
    与传统分布式数据库相比主要有以下两个区别:
    1:传统分布式数据库支持增删查改,区块链只支持查找和插入,对区块不能进行删除和修改。
    这里写图片描述
    2:传统的分布式数据库一般都是主从结构:master和slaves的结构,为了保证高可用,通过备用master来实现,而区块链是一个去中心化的数据库。没有主从结构。

    区块链和比特币:

    说起区块链,大多数人都会谈起比特币。但区块链并不等于是比特币,现在已经是区块链3.0时代,而比特币只是区块链1.0时代的产物。

    区块链的进化方式是:

    1. ▪ 区块链1.0——数字货币
    2. ▪ 区块链2.0——数字资产与智能合约
    3. ▪ 区块链3.0——各种行业分布式应用落地

    区块链的分类:
           公有区块链(PublicBlockChains)
           公有区块链是指:世界上任何个体或者团体都可以发送交易,且交易能够获得该区块链的有效确认,任何人都可以参与其共识过程。公有区块链是最早的区块链,也是应用最广泛的区块链,各大bitcoins系列的虚拟数字货币均基于公有区块链,世界上有且仅有一条该币种对应的区块链。
           联合(行业)区块链(ConsortiumBlockChains)
           行业区块链:由某个群体内部指定多个预选的节点为记账人,每个块的生成由所有的预选节点共同决定(预选节点参与共识过程),其他接入节点可以参与交易,但不过问记账过程(本质上还是托管记账,只是变成分布式记账,预选节点的多少,如何决定每个块的记账者成为该区块链的主要风险点),其他任何人可以通过该区块链开放的API进行限定查询。
           私有区块链(privateBlockChains)
           私有区块链:仅仅使用区块链的总账技术进行记账,可以是一个公司,也可以是个人,独享该区块链的写入权限,本链与其他的分布式存储方案没有太大区别。(Dec2015)保守的巨头(传统金融)都是想实验尝试私有区块链,而公链的应用例如bitcoin已经工业化,私链的应用产品还在摸索当中。

    通过python 实现简单的区块链

    import hashlib
    import json
    from time import time
    from typing import Any, Dict, List, Optional
    from urllib.parse import urlparse
    from uuid import uuid4
    
    
    from flask import Flask, jsonify, request
    import requests
    
    class Blockchain:
        def __init__(self):
            self.current_transactions = []
            self.chain = []
            self.nodes = set()
    
            # 创建创世块
            self.new_block(previous_hash='1', proof=100)
    
        def register_node(self, address: str) -> None:
            """
            Add a new node to the list of nodes
    
            :param address: Address of node. Eg. 'http://192.168.0.5:5000'
            """
    
            parsed_url = urlparse(address)
            self.nodes.add(parsed_url.netloc)
    
        def valid_chain(self, chain: List[Dict[str, Any]]) -> bool:
            """
            Determine if a given blockchain is valid
    
            :param chain: A blockchain
            :return: 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
                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) -> bool:
            """
            共识算法解决冲突
            使用网络中最长的链.
    
            :return:  如果链被取代返回 True, 否则为False
            """
    
            neighbours = self.nodes
            new_chain = None
    
            # We're only looking for chains longer than ours
            max_length = len(self.chain)
    
            # Grab and verify the chains from all the nodes in our network
            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, valid chain longer than ours
            if new_chain:
                self.chain = new_chain
                return True
    
            return False
    
        def new_block(self, proof: int, previous_hash: Optional[str]) -> Dict[str, Any]:
            """
            生成新块
    
            :param proof: The proof given by the Proof of Work algorithm
            :param previous_hash: Hash of previous Block
            :return: 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 of transactions
            self.current_transactions = []
    
            self.chain.append(block)
            return block
    
        def new_transaction(self, sender: str, recipient: str, amount: int) -> int:
            """
            生成新交易信息,信息将加入到下一个待挖的区块中
    
            :param sender: Address of the Sender
            :param recipient: Address of the Recipient
            :param amount: Amount
            :return: The index of the Block that will hold this transaction
            """
            self.current_transactions.append({
                'sender': sender,
                'recipient': recipient,
                'amount': amount,
            })
    
            return self.last_block['index'] + 1
    
        @property
        def last_block(self) -> Dict[str, Any]:
            return self.chain[-1]
    
        @staticmethod
        def hash(block: Dict[str, Any]) -> str:
            """
            生成块的 SHA-256 hash值
    
            :param block: Block
            """
    
            # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes
            block_string = json.dumps(block, sort_keys=True).encode()
            return hashlib.sha256(block_string).hexdigest()
    
        def proof_of_work(self, last_proof: int) -> int:
            """
            简单的工作量证明:
             - 查找一个 p' 使得 hash(pp') 以4个0开头
             - p 是上一个块的证明,  p' 是当前的证明
            """
    
            proof = 0
            while self.valid_proof(last_proof, proof) is False:
                proof += 1
    
            return proof
    
        @staticmethod
        def valid_proof(last_proof: int, proof: int) -> bool:
            """
            验证证明: 是否hash(last_proof, proof)以4个0开头
    
            :param last_proof: Previous Proof
            :param proof: Current Proof
            :return: True if correct, False if not.
            """
    
            guess = f'{last_proof}{proof}'.encode()
            guess_hash = hashlib.sha256(guess).hexdigest()
            return guess_hash[:4] == "0000"
    
    
    # Instantiate the Node
    app = Flask(__name__)
    
    # Generate a globally unique address for this node
    node_identifier = str(uuid4()).replace('-', '')
    
    # Instantiate the Blockchain
    blockchain = Blockchain()
    
    
    @app.route('/mine', methods=['GET'])
    def mine():
        # 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)
    
        # 给工作量证明的节点提供奖励.
        # 发送者为 "0" 表明是新挖出的币
        blockchain.new_transaction(
            sender="0",
            recipient=node_identifier,
            amount=1,
        )
    
        # Forge the new Block by adding it to the chain
        block = blockchain.new_block(proof, None)
    
        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():
        values = request.get_json()
    
        # 检查POST数据
        required = ['sender', 'recipient', 'amount']
        if not all(k in values for k in required):
            return 'Missing values', 400
    
        # Create a new Transaction
        index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])
    
        response = {'message': f'Transaction will be added to Block {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 was replaced',
                'new_chain': blockchain.chain
            }
        else:
            response = {
                'message': 'Our chain is authoritative',
                'chain': blockchain.chain
            }
    
        return jsonify(response), 200
    
    
    if __name__ == '__main__':
        from argparse import ArgumentParser
    
        parser = ArgumentParser()
        parser.add_argument('-p', '--port', default=5000, type=int, help='port to listen on')
        args = parser.parse_args()
        port = args.port
    
        app.run(host='127.0.0.1', port=port)

    对代码作出解释:

    1. Blockchain类:区块链类,在构造函数中有两个列表,一个是存储区块链,一个是存储交易
    2. block:区块,每个区块包含属性,索引(index),Unix时间戳(timestamp),交易列表,工作量证明,以及前一个区块的Hash值。
    3. new_block:生成一个新的区块方法
    4. new_transaction:生成新交易信息,信息将加入到下一个代挖的区块中。
    5. proof_of_word:简单的工作量证明,矿工通过工作量来得到奖励,对应的比特币,矿工挖矿,就是在运行这个方法,到啦proof,然后得到比特币奖励。我们的例子是要求开头为4个0,修改开头的0个数,你会发现多一个零会大大增加计算出结果所需的时间。
    6. valid_proof:验证得出的工作量证明是否正确。
    7. register_node:注册新的节点,这个是完成分布式区块链的主要方法。
    8. resolve_conflicts:解决区块链冲突问题,不同的客户端可能会有不同的链,通过该方法获取到最长的有效率作为客户端的区块链

    通过Flask框架,将网络请求映射到python函数:

    1:/transactions/new 创建一个交易并添加到区块
    2:/mine 告诉服务器去挖掘新的区块
    3:/chain 返回整个区块链
    4:/nodes/register 注册节点
    5:/nodes/resolve 解决冲突

    通过Postman和API进行交互

    1:打开8000,8001两个不同端口模拟两个客户端。

    python blockchain.py -p 8000
    python blockchain.py -p 8001

    2:将8001注册到8000端口中:
    这里写图片描述
    3:在8001端口挖矿:
    这里写图片描述
    4:调用resolve接口,将8001端口的链同步到8000端口
    这里写图片描述
    5:查看8000端口的链:
    这里写图片描述

           到这里基本区块链就完成啦,生成交易,并将交易存到以下一个待挖的测试,这里就不在过多的掩饰,基本是一样的测试方法。测试过程中对应对应的命令行输出如下:这里写图片描述

    展开全文
  • 区块链Python-源码

    2021-02-15 11:14:10
    区块链Python 遵循@dvf有关准则,为学习目的而。 使用Flask通过REST公开服务。 安装 确保已安装 。 安装 。 $ pip install pipenv 安装要求 $ pipenv install 运行服务器: $ pipenv run python blockchain.py ...
  • 区块链Python 设置 1.创建一个名为wallet的项目目录,并进入cd。 将hd-wallet派生工具克隆到此文件夹中,并按照其README.md上的说明进行安装。 一种。 git clone b。 cd高清钱包衍生 C。 php -r“ readfile(' '...
  • 区块链Python HD(分层确定性)钱包可以允许从单个种子短语生成许多crpyto钱包。这是一个从根节点开始的公共/私有密钥树,该根节点是主节点。任何节点都可以有多个子代。主私钥的唯一目的是重新生成钱包树,并且...
  • 15个区块链Python-源码

    2021-02-18 14:13:41
    15个区块链Python 依存关系: 必须在您的操作系统(任何版本5或7)上安装PHP。 您将需要克隆hd-wallet-derive工具。 位Python比特币库。 web3.py Python以太坊库。 库: 将熊猫作为pd导入将numpy导入为np 导入子...
  • 区块链Python:从头开始构建的具有不同端点的公共分散网络,以支持典型区块链的必要功能
  • Python实现的简单BlockChain 这是我在[在Python中构建简单的区块链]中的帖子的源代码。 要求 Python3.5 烧瓶 python请求 贡献 请随时提出拉取请求:)
  • 简单区块链Python实现

    2019-11-04 16:31:39
    什么是区块链 区块链是一种数据结构,也是一个分布式数据库。 从技术上来看:区块是一种记录交易的数据结构,反映了一笔交易的资金流向。系统中已经达成的交易的区块连接在一起形成了一条主链,所有参与计算的节点都...

    什么是区块链

    区块链是一种数据结构,也是一个分布式数据库。

    从技术上来看:区块是一种记录交易的数据结构,反映了一笔交易的资金流向。系统中已经达成的交易的区块连接在一起形成了一条主链,所有参与计算的节点都记录了主链或主链的一部分。
    在这里插入图片描述

    组成

    区块头

    区块头主要包含的三组元数据分别是:(1)用于连接前面的区块、索引自父区块哈希值的数据;(2)挖矿难度、时间戳、Nonce(随机数,用于工作量证明算法的计数器,也可理解为记录解密该区块相关数学题的答案的值);(3)能够总结并快速归纳校验区块中所有交易数据的Merkle(默克尔)树根数据。当然区块头不仅仅包含这些元数据,还有其他比如:版本号、难度值等。
    从这个结构来看,区块链的大部分功能都由区块头实现。

    区块主体

    区块主体所记录的交易信息是区块所承载的任务数据,具体包括交易双方的私钥、交易的数量、电子货币的数字签名等。

    比特币系统大约每10分钟会创建一个区块,这个区块包含了这段时间里全网范围内发生的所有交易。每一个区块都保存了上一个区块的哈希值,使得每个区块都能找到其前一个区块,这样就将这些区块连接起来,形成了一个链式的结构。
    在这里插入图片描述

    区块字段

    • Difficulty 此区块的难度级别
    • ExtraData 与此区块相关的附加数据 在区块链早期使用比较多,现在用的很少
    • gasLimit 当前区块允许使用的最大gas, gas表示一种计算量, 使用的算力单位
    • gasUsed 当前区块已经使用的gas
    • Hash 当前区块的哈希值。如果区块没有被确认,这个字段会是null值
    • LogsBloom 由日志信息组成的一个Bloom过滤器 (数据结构),区块没被确认- 是值为null
    • Miner 取得该区块记账权的矿工
    • mixHash 一个Hash值,当与nonce组合时,证明此区块已经执行了足够的计算
    • nonce 一个Hash值,当与mixHash组合时,证明此区块已经执行了足够的计算
    • Number 当前区块的计数(创世纪块的区块序号为0,对于每个后续区块,区块序号都增加1)
    • parentHash 父区块头的Hash值(这也是使得区块变成区块链的原因)
    • receiptsRoot 包含此区块所列的所有交易收据的树的根节点Hash值
    • Sha3Uncles 数据块的哈希值
    • Size 当前区块的字节大小
    • stateRoot 区块状态树的根哈希
    • Timestamp 区块打包时的unix时间戳
    • totalDifficulty 区块链到当前区块的总难度
    • Transactions 交易的对象
    • transactionsRoot 区块的交易树的根哈希
    • Uncles 叔哈希数组 树区块详见 https://blog.csdn.net/weixin_42874184/article/details/81735695

    在这里插入图片描述

    Python实现

    实现了工作量证明,难度计算,哈希部分

    import hashlib
    import datetime
    import random
     
    class Block:
        def __init__(self, index, transaction, pre_hash, difficulty, nonce):
            self.index = index
            self._timestamp = datetime.datetime.now()
            self._transaction = transaction
            self._pre_hash = pre_hash
            self._nonce = nonce
            self._difficulty = difficulty
            self.hash = self.gen_hash()
     
        @property
        def get_hash(self):
            return self.hash
     
        @property
        def get_index(self):
            return self.index
     
        @property
        def get_transaction(self):
            return self._transaction
     
        @property
        def get_difficulty(self):
            return self._difficulty
     
        @property
        def get_timestamp(self):
            return self._timestamp
     
        @property
        def get_pre_hash(self):
            return self._pre_hash
     
        @property
        def get_nonce(self):
            return self._nonce
     
        def gen_hash(self):
            sha = hashlib.sha256()
            data = str(self.index) + str(self._timestamp) + str(self._transaction) + str(self._pre_hash) + str(self._nonce) + str(self._difficulty)
            sha.update(data.encode("utf8"))
            return sha.hexdigest()
     
     
    class Blockchain:
        def __init__(self, max_blocks):
            self._chain_list = [Block(0, "The First Block", '0', '1', random.randrange(0, 99999))]
            self._previous_block = self._chain_list[0]
            self._current_block = 1
            self.max_blocks = max_blocks
     
        @staticmethod
        def create_next_block(self):
            last_block = self._chain_list[self._current_block - 1]
            last_difficulty = last_block.get_difficulty
            this_index = last_block.index + 1
            this_transaction = "New Block " + str(this_index) + " has been generated successfully."
            nonce = random.randrange(0, 99999)
            this_difficulty = self.proof_of_work(nonce)
            pre_hash = last_block.hash
            self._chain_list.append(Block(this_index, this_transaction, pre_hash, this_difficulty, nonce))
            self._current_block += 1
     
        def last_block(self):
            return self._chain_list[-1]
     
        def proof_of_work(self, nonce):
            proof = 0
            while self.valid_proof(self, proof, nonce) is False:
                proof += 1
            return proof
     
        @staticmethod
        def valid_proof(self, proof, nonce):
            guess = f'{proof}{nonce}'.encode()
            guess_hash = hashlib.sha256(guess).hexdigest()
            pattern = "0000"
            return guess_hash[:len(pattern)] == pattern
     
        def run(self):
            for i in range(self.max_blocks):
                self.create_next_block(self)
     
        def show_block(self, index):
            print("----------------------------------------")
            print("ID: ", self._chain_list[index].get_index)
            print("Time", self._chain_list[index].get_transaction)
            print("Cur Hash", self._chain_list[index].get_hash)
            print("Pre Hash", self._chain_list[index].get_pre_hash)
            print("Difficulty", self._chain_list[index].get_difficulty)
            print("Trans", self._chain_list[index].get_transaction)
            print("Nonce", self._chain_list[index].get_nonce)
            print("----------------------------------------")
     
     
    myBlockChain = Blockchain(100)
    myBlockChain.run()
    for i in range(myBlockChain.max_blocks):
        myBlockChain.show_block(i)
    

    在这里插入图片描述

    参考文献

    https://segmentfault.com/a/1190000014483104
    https://blog.csdn.net/qq874455953/article/details/83718022

    更多内容访问 omegaxyz.com
    网站所有代码采用Apache 2.0授权
    网站文章采用知识共享许可协议BY-NC-SA4.0授权
    © 2020 • OmegaXYZ-版权所有 转载请注明出处

    展开全文
  • 区块链Python初试

    2019-01-12 21:06:02
    在此基础上稍作修改:... 使用了psutil模块查看运行时的硬件数据。 以下是第一次尝试的代码: import hashlib import json from time import time from urllib.parse import urlparse from uuid import uuid...

    在此基础上稍作修改:https://www.cnblogs.com/kidney/p/7627145.html

    使用了psutil模块查看运行时的硬件数据。

    以下是第一次尝试的代码:

    import hashlib
    import json
    from time import time
    from urllib.parse import urlparse
    from uuid import uuid4
    
    import requests
    from flask import Flask, jsonify, request
    
    
    class Blockchain:
        def __init__(self):
            self.current_transactions = []
            self.chain = []
            self.nodes = set()
    
            # Create the genesis block
            self.new_block(previous_hash='1', proof=100)
    
        def register_node(self, address):
            """
            Add a new node to the list of nodes
    
            :param address: Address of node. Eg. 'http://192.168.0.5:5000'
            """
    
            parsed_url = urlparse(address)
            if parsed_url.netloc:
                self.nodes.add(parsed_url.netloc)
            elif parsed_url.path:
                # Accepts an URL without scheme like '192.168.0.5:5000'.
                self.nodes.add(parsed_url.path)
            else:
                raise ValueError('Invalid URL')
    
        def valid_chain(self, chain):
            """
            Determine if a given blockchain is valid
    
            :param chain: A blockchain
            :return: 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
                last_block_hash = self.hash(last_block)
                if block['previous_hash'] != last_block_hash:
                    return False
    
                # Check that the Proof of Work is correct
                if not self.valid_proof(last_block['proof'], block['proof'], last_block_hash):
                    return False
    
                last_block = block
                current_index += 1
    
            return True
    
        def resolve_conflicts(self):
            """
            This is our consensus algorithm, it resolves conflicts
            by replacing our chain with the longest one in the network.
    
            :return: True if our chain was replaced, False if not
            """
    
            neighbours = self.nodes
            new_chain = None
    
            # We're only looking for chains longer than ours
            max_length = len(self.chain)
    
            # Grab and verify the chains from all the nodes in our network
            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, valid chain longer than ours
            if new_chain:
                self.chain = new_chain
                return True
    
            return False
    
        def new_block(self, proof, previous_hash):
            """
            Create a new Block in the Blockchain
    
            :param proof: The proof given by the Proof of Work algorithm
            :param previous_hash: Hash of previous Block
            :return: 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 of transactions
            self.current_transactions = []
    
            self.chain.append(block)
            return block
    
        def new_transaction(self, sender, recipient, amount):
            """
            Creates a new transaction to go into the next mined Block
    
            :param sender: Address of the Sender
            :param recipient: Address of the Recipient
            :param amount: Amount
            :return: The index of the Block that will hold this transaction
            """
            self.current_transactions.append({
                'sender': sender,
                'recipient': recipient,
                'amount': amount,
            })
    
            return self.last_block['index'] + 1
    
        @property
        def last_block(self):
            return self.chain[-1]
    
        @staticmethod
        def hash(block):
            """
            Creates a SHA-256 hash of a Block
    
            :param block: Block
            """
    
            # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes
            block_string = json.dumps(block, sort_keys=True).encode()
            return hashlib.sha256(block_string).hexdigest()
    
        def proof_of_work(self, last_block):
            """
            Simple Proof of Work Algorithm:
    
             - Find a number p' such that hash(pp') contains leading 4 zeroes
             - Where p is the previous proof, and p' is the new proof
    
            :param last_block: <dict> last Block
            :return: <int>
            """
    
            last_proof = last_block['proof']
            last_hash = self.hash(last_block)
    
            proof = 0
            while self.valid_proof(last_proof, proof, last_hash) is False:
                proof += 1
    
            return proof
    
        @staticmethod
        def valid_proof(last_proof, proof, last_hash):
            """
            Validates the Proof
    
            :param last_proof: <int> Previous Proof
            :param proof: <int> Current Proof
            :param last_hash: <str> The hash of the Previous Block
            :return: <bool> True if correct, False if not.
    
            """
    
            guess = f'{last_proof}{proof}{last_hash}'.encode()
            guess_hash = hashlib.sha256(guess).hexdigest()
            return guess_hash[:4] == "0000"
    
    
    # Instantiate the Node
    app = Flask(__name__)
    
    # Generate a globally unique address for this node
    node_identifier = str(uuid4()).replace('-', '')
    
    # Instantiate the Blockchain
    blockchain = Blockchain()
    
    
    @app.route('/mine', methods=['GET'])
    def mine():
        # We run the proof of work algorithm to get the next proof...
        last_block = blockchain.last_block
        proof = blockchain.proof_of_work(last_block)
    
        # We must receive a reward for finding the proof.
        # The sender is "0" to signify that this node has mined a new coin.
        blockchain.new_transaction(
            sender="0",
            recipient=node_identifier,
            amount=1,
        )
    
        # Forge the new Block by adding it to the chain
        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():
        values = request.get_json()
    
        # Check that the required fields are in the POST'ed data
        required = ['sender', 'recipient', 'amount']
        if not all(k in values for k in required):
            return 'Missing values', 400
    
        # Create a new Transaction
        index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])
    
        response = {'message': f'Transaction will be added to Block {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 was replaced',
                'new_chain': blockchain.chain
            }
        else:
            response = {
                'message': 'Our chain is authoritative',
                'chain': blockchain.chain
            }
    
        return jsonify(response), 200
    
    
    if __name__ == '__main__':
        import psutil,datetime
        from argparse import ArgumentParser
    
        parser = ArgumentParser()
        parser.add_argument('-p', '--port', default=5000, type=int, help='port to listen on')
        args = parser.parse_args()
        port = args.port
        mem = psutil.virtual_memory()
        cputimes = psutil.cpu_times(percpu=True)
        print(cputimes)
        cpucount = psutil.cpu_count(logical=False)
        print(cpucount)
        print('-----------------------------------------------------------------')
        print(mem,mem.total,mem.free)
        print('-----------------------------------------------------------------')
        app.run(host='0.0.0.0', port=port)

    接下来的工作室修改PoW的加密算法,再用psutil查看比较各种算法的情况。总之,对于我来说,任重而道远。

    展开全文
  • 区块链python演示

    2018-01-30 17:25:00
    创建一个新块 并添加到新的区块链中 并重置交易 block = blockchain.new_block(proof) response = { ' message ' : " New Block Forged " , ' index ' : block[ ' index ' ], ' transactions ' : ...
    # -*- coding: utf-8 -*-
    """
    Created on Tue Jan 30 08:46:36 2018
    block:每个区块包含属性:索引(index),Unix时间戳(timestamp),交易列表(transactions),工作量证明(稍后解释)以及前一个区块的Hash值。
    @author: Administrator
    """
    import hashlib
    import json
    import requests
    from time import time
    from uuid import uuid4
    from flask import Flask, jsonify, request
    from textwrap import dedent
    from urllib.parse import urlparse
    
    
    class Blockchain(object):
         #初始化变量
        def __init__(self):
            self.chain = [] #当前链长度为0
            self.current_transactions = [] #当前交易量为空
            self.nodes = set()
             # Create the genesis block
            self.new_block(previous_hash=1, proof=100)
        #注册新节点
        def register_node(self, address):
            """
            Add a new node to the list of nodes
            :param address: <str> Address of node. Eg. 'http://192.168.0.5:5000'
            :return: None
            """
            parsed_url = urlparse(address)
            self.nodes.add(parsed_url.netloc)
          #创建新块   
        def new_block(self, proof, previous_hash=None):
            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 of transactions
            self.current_transactions = []
    
            self.chain.append(block)
            return block
         #创建新交易 并返回该记录将被添加到的区块(下一个待挖掘的区块)的索引
        def new_transaction(self, sender, recipient, amount):
            self.current_transactions.append({
                'sender': sender,
                'recipient': recipient,
                'amount': amount,
            })
    
            return self.last_block['index'] + 1
         #静态哈希方法
        @staticmethod
        def hash(block):
            block_string = json.dumps(block, sort_keys=True).encode()
            return hashlib.sha256(block_string).hexdigest()
        #上一区块
        @property
        def last_block(self):
            return self.chain[-1]
        """
            简单的工作量证明:
             - 查找一个 p' 使得 hash(pp') 以4个0开头
             - p 是上一个块的证明,  p' 是当前的证明
            :param last_proof: <int>
            :return: <int>
        """
       #工作量验证工作
        def proof_of_work(self, last_proof):
          
            proof = 0
            while self.valid_proof(last_proof, proof) is False:
                proof += 1
    
            return proof
    
        @staticmethod
        def valid_proof(last_proof, proof):
            """
            验证证明: 是否hash(last_proof, proof)以4个0开头?
            :param last_proof: <int> Previous Proof
            :param proof: <int> Current Proof
            :return: <bool> True if correct, False if not.
            """
            #F-string  提高效率
            guess = f'{last_proof}{proof}'.encode()
            guess_hash = hashlib.sha256(guess).hexdigest()
            return guess_hash[:4] == "0000"
         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
                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):
            """
            共识算法解决冲突
            使用网络中最长的链.
            :return: <bool> True 如果链被取代, 否则为False
            """
    
            neighbours = self.nodes
            new_chain = None
    
            # We're only looking for chains longer than ours
            max_length = len(self.chain)
    
            # Grab and verify the chains from all the nodes in our network
            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, valid chain longer than ours
            if new_chain:
                self.chain = new_chain
                return True
    
            return False
    
    # Instantiate our Node
    #s实例化Flask
    app = Flask(__name__)
    
    # Generate a globally unique address for this node
    #创建地址
    node_identifier = str(uuid4()).replace('-', '')
    
    # 初始化区块链 创建创世快
    blockchain = Blockchain()
    
    
    #开始挖矿
    @app.route('/mine', methods=['GET'])
    def mine():
         # 获取上一个区块 的proof 得到下一个区块的proof
        last_block = blockchain.last_block
        #上一个证明
        last_proof = last_block['proof']
        #工作量证明
        proof = blockchain.proof_of_work(last_proof)
        #添加交易
        # 给工作量证明的节点提供奖励.
        # 发送者为 "0" 表明是新挖出的币
        blockchain.new_transaction(
            sender="0",
            recipient=node_identifier,
            amount=1,
        )
    
        # 创建一个新块 并添加到新的区块链中  并重置交易
        block = blockchain.new_block(proof)
    
        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():
         #获取传送过来的json参数
        values = request.get_json()
    
        # Check that the required fields are in the POST'ed data
        required = ['sender', 'recipient', 'amount']
        if not all(k in values for k in required):
            return 'Missing values', 400
    
        #创建一个新交易 返回当前交易所引  (发送方 接收方 数量..)
        index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])
    
        response = {'message': f'Transaction will be added to Block {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 was replaced',
                'new_chain': blockchain.chain
            }
        else:
            response = {
                'message': 'Our chain is authoritative',
                'chain': blockchain.chain
            }
    
        return jsonify(response), 200
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000)

     

    转载于:https://www.cnblogs.com/x0216u/p/8386166.html

    展开全文
  • 构建区块链 python(三)

    千次阅读 2020-04-13 10:05:35
    步骤3:与我们的区块链交互 python blockchain.py #让我们通过创建一个新交易 POST 请求 #http://localhost:5000/transactions/new 包含我们的交易结构的主体: $ curl -X POST -H "Content-Type: application/json...
  • 构建区块链 python(二)

    千次阅读 2020-04-12 13:07:42
    步骤2:将我们的区块链作为API 我们将使用Python Flask框架。这是一个微框架,可以轻松将端点映射到Python函数。这使我们可以使用HTTP请求通过Web与我们的区块链进行对话。 我们将创建三种方法: /transactions/new...
  • 区块链简介。 python区块链代码示例: 区块链难篡改,但信息冗余。 区块链的链式结构,和过去的族谱很像。
  • 构建区块链 python(一)

    千次阅读 2020-04-12 08:42:44
    构建区块链 前言 小编认为学习区块链如何工作的最快方法是建立一个区块链。虽然网上有很多教程或视频,小编也一一浏览过,但是觉得那些示例效果…小编喜欢边做边学,小编希望在看过这篇文章之后您将拥有一个运行...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 2,527
精华内容 1,010
关键字:

区块链python

python 订阅