blockchain has no attribute chain?

来源:3-7 交易接口实现

以太势科技

2018-07-04

http://img.mukewang.com/szimg/5b3c53f70001471809490458.jpg

http://img.mukewang.com/szimg/5b3c53f70001515208090394.jpg

你好,老师,我想请教下为什么我一开始就出现这个 attribute 的错误?

写回答

2回答

以太势科技

提问者

2018-07-07

import hashlib
from time import time

from flask import Flask, jsonify, request


class Blockchain:

   def __int__(self):
       self.chain = []
       self.current_transactions = []

       self.new_block(proof=100, previous_hash=1)

   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.last_block)
       }

       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]

   def proof_of_work(self, last_proof: int):
       proof = 0
       while self.valid_proof(last_proof, proof) is False:
           proof += 1
       print(proof)
       return proof

   def valid_proof(self, last_proof: int, proof: int):
       guess = f'{last_proof}{proof}'.encode()
       guess_hash = hashlib.sha256(guess).hexdigest()
       print(guess_hash)
       return guess_hash[0:4] == "0000"


app = Flask(__name__)
blockchain = Blockchain()


@app.route('/transactions/new', methods=['POST'])
def new_transaction():
   values = request.get_json()
   required = ["sender", "recipient", "amount"]

   if values is None:
       return "Missing Values", 400

   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('/mine', methods=['GET'])
def mine():
   return "we'll mine a new block"


@app.route('/chain', methods=['GET'])
def full_chain():
   response = {
       'chain': blockchain.chain,
       'length': len(blockchain.chain)
   }

   return jsonify(response), 200


if __name__ == '__main__':
   app.run(host='0.0.0.0', port=5000)


0
0

Tiny

2018-07-06

检查下 在init 中是否定义了属性: self.chain = [] 

0
2
Yhyyy
回复
以太势科技
您好解决了吗?我也出现了同样的问题
2018-11-10
共2条回复

区块链入门与去中心化应用实战,快速入门区块链技术

一门课搞懂区块链核心原理,快速入门去中心化Dapp开发

1259 学习 · 208 问题

查看课程