Ejemplo n.º 1
0
def get_blockchain():
    blockchain = Blockchain()
    blockchain_db = Table("blockchain", "number", "nonce", "hash_previous", "hash_current", "data")

    for block_db in blockchain_db.getall():
        blockchain.add_block(Block(int(block_db.get('number')), int(block_db.get('nonce')), block_db.get('hash_previous'), block_db.get('data')))
    return blockchain
Ejemplo n.º 2
0
 def __init__(self):
     super().__init__()
     self.setupUi(self)
     # 获取用户ID 和 注册时间
     self.user_id = str(uuid4())
     self.registration_time = self.get_format_time()
     # 新用户红利 初始余额
     self.balance_min = INIT_BALANCE
     self.balance_max = INIT_BALANCE
     # 设置当前应用主链
     self.block_chain = Blockchain()
     # 设置交易子窗口
     self.subpage_transaction = Form_TransactionPage()
     self.subpage_transaction.hide()
     # 根据信息 重设界面
     self.reset_page()
     # 控件列表
     self.buttons = [self.pushButton_chain, self.pushButton_balance,
                     self.pushButton_transaction, self.pushButton_mine]
     # 初始化信号与槽连接
     self.handle_init()
     # 多节点要素补充
     self.users = set()
     self.users.add('0')
     self.users.add('Test')
     self.ip_port = IP_PORT
     # 解决信号与槽跨线程
     self.signal_recv_msg.connect(self.show_chatting_message)
     # 创建附属监听线程
     self.is_running = True
     self.listen_thread = ServerThread(owner=self, ip_port=('', self.ip_port[1]))
     self.listen_thread.start()
Ejemplo n.º 3
0
def main():
    blockchain = Blockchain()
    database = ["Hello", "There", "How you doing?"]

    num = 0
    for data in database:
        num += 1
        blockchain.mining(Block(data, num))

    for block in blockchain.chain:
        print(block)

    print(blockchain.isValid())
Ejemplo n.º 4
0
def create_chain_from_dump(chain_dump):
    generated_blockchain = Blockchain()
    generated_blockchain.create_genesis_block()
    for idx, block_data in enumerate(chain_dump):
        if idx == 0:
            continue  # skip genesis block
        block = Block(block_data["index"], block_data["transactions"],
                      block_data["timestamp"], block_data["previous_hash"],
                      block_data["nonce"])
        proof = block_data['hash']
        added = generated_blockchain.add_block(block, proof)
        if not added:
            raise Exception("The chain dump is tampered!!")
    return generated_blockchain
def add_peer(new_blockchain: Blockchain):
    global blockchain

    if blockchain is None or len(new_blockchain) >= len(
            blockchain):  # Pseudo-consensus
        validated_blockchain = Blockchain(difficulty)
        for block in new_blockchain.blocks:
            if block.index != 0:
                added = validated_blockchain.add_block_from_peer(block)
                if not added:
                    logging.error("Bad blockchain. No peer added.")
                    return
            else:
                validated_blockchain.blocks[0] = block

        if not validated_blockchain.is_valid():
            logging.error("Bad blockchain. No peer added.")
            return

        blockchain = validated_blockchain
def reading_network():
    global blockchain

    while True:
        try:
            data = socket_sub.recv_json()
            if "operation" in data:
                parameters = data["parameters"]
                if data["operation"] == "add_transaction":
                    add_transaction(parameters)
                elif data["operation"] == "add_peer":
                    add_peer(Blockchain.from_dict(parameters["blockchain"]))
                elif data["operation"] == "consensus":
                    if blockchain is not None:
                        socket.send_json({
                            "operation": "consensus_resp",
                            "parameters": {
                                "blockchain": blockchain.to_dict()
                            },
                        })
                elif data["operation"] == "consensus_resp":
                    peer_blockchain = Blockchain.from_dict(
                        parameters["blockchain"])
                    if blockchain is None or (
                            len(peer_blockchain) > len(blockchain)
                            and peer_blockchain.is_valid()):
                        blockchain = peer_blockchain
                        socket.send_json({
                            "operation": "consensus_resp",
                            "parameters": {
                                "blockchain": blockchain.to_dict()
                            },
                        })
                elif data["operation"] == "add_block":
                    add_block(parameters)

        except:
            traceback.print_exc()
Ejemplo n.º 7
0
def mine():
    global blockchain
    if blockchain == None:
        blockchain = Blockchain(difficulty)
        blockchain.create_genesis_block()
        return "Blockchain created \n", 200
    else:
        blockchain.mine_block()
        return "Block mined\n", 200
Ejemplo n.º 8
0
 def mine_call(self):
     # need to call the mining function
     global blockchain
     if not blockchain:
         blockchain = Blockchain(difficulty)
         blockchain.create_genesis_block(wallet)
     else:
         blockchain.mine_block(wallet)
     print(blockchain.tokens)
     self.define_block(blockchain.blocks[-1])
     data = blockchain.to_dict()
     dataJson = json.dumps(data).encode()
     socket.send_multipart([b'chain', dataJson])
Ejemplo n.º 9
0
def reading_network():
    global blockchain
    global ConnectionWrite
    while True:
        [topic_val, msg_val] = socket_sub.recv_multipart()
        topico = topic_val.decode()
        data = json.loads(msg_val.decode())
        if topico == 'chain':
            if blockchain and len(blockchain.blocks) < len(
                    data['blocks']) or not blockchain:
                new = Blockchain(difficulty, data['blocks'])
                if new.verify():
                    blockchain = new
                    print(blockchain.tokens)
                    ConnectionWrite.write_block.emit(str(
                        blockchain.blocks[-1]))
                else:
                    print("Received weird block")
        if topico == 'transaction':
            if blockchain:
                blockchain.add_transaction(receiver=data["receiver"],
                                           sender=data["sender"],
                                           amount=data["amount"],
                                           signature=data["signature"])
Ejemplo n.º 10
0
def main():
    blockchain = Blockchain()
    database = ["hello", "goodbye", "test", "DATA here", "test2"]

    num = 0

    for data in database:
        num += 1
        blockchain.mine(Block(num, data=data))

    for block in blockchain.chain:
        print(block)

    print(blockchain.isValid())
    # i try to change data in blck number 2 without valid nonce
    blockchain.chain[2].data = "NEW DATA"
    blockchain.mine(blockchain.chain[2])
    print(blockchain.isValid())
Ejemplo n.º 11
0
def sync_chain(address):
    req = requests.get(address)
    global CyberCellCoin
    CyberCellCoin = Blockchain()
    CyberCellCoin.nodes = [address + "/peers"]
    recived = req.json()
    CyberCellCoin.chain =  []
    empty = Block()
    for index in range(len(recived)):
        new = copy.copy(empty)
        new.__dict__ = recived[index]
        CyberCellCoin.add(new)
Ejemplo n.º 12
0
    def mine_call(self):
        global blockchain
        if not blockchain:
            blockchain = Blockchain(difficulty)
            blockchain.create_genesis_block(wallet)
        else:
            blockchain.mine_block(wallet)

        self.define_block(blockchain.chain[-1])
        chain = blockchain.to_dict()
        chain_data = json.dumps({
            "length": len(chain),
            "chain": chain
        }).encode()

        socket.send_multipart([b'chain', chain_data])
Ejemplo n.º 13
0
def reading_network():
    global blockchain
    global ConnectionWrite
    while True:
        [topic_val, msg_val] = socket_sub.recv_multipart()
        topic = topic_val.decode()

        if (topic == "chain"):
            chain_data = json.loads(msg_val.decode())
            if (blockchain and len(blockchain.chain) < chain_data["length"]
                ) or blockchain is None:
                blockchain = Blockchain(difficulty, chain_data["chain"])

                for block in blockchain.chain:
                    if (block.verify_block() != true):
                        print("ERROR: block not valid")
                        return
                ConnectionWrite.write_block.emit(str(blockchain.chain[-1]))
    def mine_call(self):
        global blockchain

        if blockchain is None:
            self.consensus()
            if blockchain is None:
                blockchain = Blockchain.create(difficulty, wallet)
        else:
            result = blockchain.mine_block(wallet)
            if not result:
                logging.info("No transaction to mine")
            else:
                chain_length = len(blockchain.blocks)
                self.consensus()
                if chain_length == len(blockchain.blocks):
                    socket.send_json({
                        "operation": "add_block",
                        "parameters": {
                            "block": blockchain.head.to_dict(),
                        },
                    })
        logging.info(f"HEAD: {blockchain.head}")
        self.define_block(blockchain.head)
Ejemplo n.º 15
0
class MainWindow(QWidget, Ui_Form_HomePage):
    signal_recv_msg = pyqtSignal(str, str, str)

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        # 获取用户ID 和 注册时间
        self.user_id = str(uuid4())
        self.registration_time = self.get_format_time()
        # 新用户红利 初始余额
        self.balance_min = INIT_BALANCE
        self.balance_max = INIT_BALANCE
        # 设置当前应用主链
        self.block_chain = Blockchain()
        # 设置交易子窗口
        self.subpage_transaction = Form_TransactionPage()
        self.subpage_transaction.hide()
        # 根据信息 重设界面
        self.reset_page()
        # 控件列表
        self.buttons = [self.pushButton_chain, self.pushButton_balance,
                        self.pushButton_transaction, self.pushButton_mine]
        # 初始化信号与槽连接
        self.handle_init()
        # 多节点要素补充
        self.users = set()
        self.users.add('0')
        self.users.add('Test')
        self.ip_port = IP_PORT
        # 解决信号与槽跨线程
        self.signal_recv_msg.connect(self.show_chatting_message)
        # 创建附属监听线程
        self.is_running = True
        self.listen_thread = ServerThread(owner=self, ip_port=('', self.ip_port[1]))
        self.listen_thread.start()

    @staticmethod
    def get_format_time(pattern="%Y-%m-%d %H:%M:%S") -> str:
        return str(time.strftime(pattern, time.localtime()))

    def get_format_info(self, title='', info=None):
        if info is None:
            info = {}
        return '{title:#^66}\n{info}\n{time:#^66}'.format(
            title=title,
            info=json.dumps(info, indent=2, ensure_ascii=False),
            time=self.get_format_time()
        )

    def reset_page(self):
        # 设置标题
        self.setWindowTitle('基于分布式账本的交易网络')
        self.subpage_transaction.setWindowTitle('交易窗口')
        # 调色板画背景
        palette = QPalette()
        palette.setBrush(QPalette.Background, QBrush(QPixmap(":images/background.png").scaled(self.size())))
        self.setPalette(palette)
        # 设置主页用户信息
        self.label_name_right.setText(self.user_id)
        self.label_time_right.setText(self.registration_time)
        self.label_balance_right.setText('{}(未入账)\t{}(已入账)'.format(self.balance_min, self.balance_max))

    def closeEvent(self, QCloseEvent):
        self.is_running = False
        self.subpage_transaction.close()
        MySocket.send_data(msg_type='Quit', msg_data='Quit', target_ip_port=self.ip_port,
                           from_user='******')

    def append_output(self, info):
        print('New Message:\t', info)
        self.textBrowser_output.append(info + '\n')

    def handle_init(self):
        self.pushButton_chain.clicked.connect(self.show_chain)
        self.pushButton_balance.clicked.connect(self.show_balance)
        self.pushButton_transaction.clicked.connect(self.open_subpage_transaction)
        self.pushButton_mine.clicked.connect(self.mine)
        self.subpage_transaction.pushButton_submit.clicked.connect(self.add_transaction)
        # 多节点按钮
        self.pushButton_node_broadcast.clicked.connect(self.broadcast_this_node)
        self.pushButton_node_list.clicked.connect(self.show_nodes)
        self.pushButton_chain_replace.clicked.connect(self.update_chain)
        # 聊天室按钮
        self.pushButton_chat.clicked.connect(self.send_chatting_message)

    def show_error_msg(self, title, msg):
        QMessageBox.warning(self, title, msg, QMessageBox.Ok)

    def show_chain(self):
        info = {
            '链': self.block_chain.chain,
            '长度': len(self.block_chain.chain)
        }
        self.append_output(info=self.get_format_info(' Show Full Chain ', info))

    def show_nodes(self):
        info = {
            '节点': list(self.block_chain.nodes),
            '节点总数': len(self.block_chain.nodes),
            '用户': list(self.users),
            '已注册用户数': len(self.users)
        }
        self.append_output(info=self.get_format_info(' Show Node List ', info))

    def get_balance_min_and_max(self):
        max_balance_dict = self.block_chain.get_max_balance()
        min_balance_dict = max_balance_dict.copy()
        for i in self.block_chain.currentTransaction:
            sender = i['sender']
            recipient = i['recipient']
            amount = i['amount']
            balance_old = float(min_balance_dict[sender]) if sender in min_balance_dict.keys() else 0.0
            min_balance_dict[sender] = balance_old - float(amount)
            balance_old = float(min_balance_dict[recipient]) if recipient in min_balance_dict.keys() else 0.0
            min_balance_dict[recipient] = balance_old + float(amount)
        return min_balance_dict, max_balance_dict

    def update_balance_min_and_max(self, min_balance_dict, max_balance_dict):
        self.balance_max = max_balance_dict[self.user_id] if self.user_id in max_balance_dict.keys() else 0.0
        self.balance_min = min_balance_dict[self.user_id] if self.user_id in min_balance_dict.keys() else 0.0
        self.label_balance_right.setText('{}(未入账)\t{}(已入账)'.format(self.balance_min, self.balance_max))

    def show_balance(self):
        min_dict, max_dict = self.get_balance_min_and_max()
        self.update_balance_min_and_max(min_dict, max_dict)
        self.append_output(info=self.get_format_info(' Show Balance True', max_dict))
        self.append_output(info=self.get_format_info(' Show Balance Current', min_dict))

    def open_subpage_transaction(self):
        self.subpage_transaction.show()
        self.subpage_transaction.lineEdit_sender.setText(self.user_id)
        self.subpage_transaction.lineEdit_sender.setEnabled(False)

    def add_transaction(self):
        p = self.subpage_transaction
        if self.is_input_legal():
            idx = self.block_chain.new_transaction(
                sender=p.lineEdit_sender.text(),
                recipient=p.lineEdit_receiver.text(),
                amount=p.lineEdit_number.text()
            )
            _i, _j = self.get_balance_min_and_max()
            self.update_balance_min_and_max(_i, _j)
            info = '{time}\t该交易信息将会被添加到 区块{idx} 在下一次挖矿后...'.format(time=self.get_format_time(), idx=idx)
            self.append_output(info=info)
            self.broadcast_last_transaction()
            p.clear()
            p.hide()
        else:
            # 隐显确保窗口置前端
            p.hide()
            p.show()

    def is_input_legal(self):
        p = self.subpage_transaction
        ans = True
        info = None
        if p.lineEdit_receiver.text() not in self.users:
            info = '接收方ID有误,用户记录查无此人'
            ans = False
        elif re.match(r'^\d+\.?\d*$', p.lineEdit_number.text()) is None:
            info = '交易数额有误,请填入正确数字'
            ans = False
        elif float(p.lineEdit_number.text()) > self.balance_min:
            info = '余额不足,请检查交易额或更新余额'
            ans = False
        if info is not None:
            self.show_error_msg(title='Error', msg=info)
            self.append_output(info='{}\t{}'.format(self.get_format_time(), info))
        return ans

    def mine(self):
        last_block = self.block_chain.last_block
        last_proof = last_block['proof']
        t = time.time()
        proof = self.block_chain.proof_of_work(last_proof)
        t = time.time() - t
        info = {
            '信息': '挖矿取得新区块Proof',
            '耗时': '{:.8f} s'.format(t),
            '工作量证明': proof
        }
        self.append_output(info=self.get_format_info(' Get New Proof ', info))

        self.block_chain.new_transaction(
            sender='0',
            recipient=self.user_id,
            amount=str(SYSTEM_REWARD)
        )

        previous_hash = self.block_chain.hash(last_block)
        block = self.block_chain.new_block(proof=proof, previous_hash=previous_hash)

        _i, _j = self.get_balance_min_and_max()
        self.update_balance_min_and_max(_i, _j)

        info = {
            '信息': "New Block Forged",
            '索引值': block['index'],
            '交易信息': block['transactions'],
            '工作量证明': block['proof'],
            '前导区块Hash': block['previous_hash'],
        }
        self.append_output(info=self.get_format_info(' Add New Block ', info))

    def broadcast_this_node(self):
        info = '{}\t{}'.format(self.get_format_time(), '登陆上线,已将本节点广播到网络中...')
        self.append_output(info=info)
        MySocket.send_data(msg_type='NewNodeAdded', msg_data=self.ip_port,
                           target_ip_port=('<broadcast>', self.ip_port[1]), from_user=self.user_id)

    def register_user_id(self, user_id):
        self.users.add(user_id)
        info = '{}\t{}'.format(self.get_format_time(), '已同步节点,并添加 用户{} 到记录'.format(user_id))
        self.append_output(info=info)

    def register_old_node(self, ip_port_from, *args, **kwargs):
        ip_port_from = tuple(ip_port_from)
        self.block_chain.nodes.add(str(ip_port_from))
        info = '{}\t{}'.format(self.get_format_time(), '收到回拨信息并将 节点 {} 添加到列表'.format(ip_port_from))
        self.append_output(info=info)
        self.register_user_id(user_id=kwargs['from_user'])

    def register_new_node(self, ip_port_from, *args, **kwargs):
        ip_port_from = tuple(ip_port_from)
        self.block_chain.nodes.add(str(ip_port_from))
        info = '{}\t{}'.format(self.get_format_time(), '已添加 节点{} 到列表,并向其回拨本节点'.format(ip_port_from))
        self.append_output(info=info)
        MySocket.send_data(msg_type='OldNodeReply', msg_data=self.ip_port, target_ip_port=ip_port_from,
                           from_user=self.user_id)
        self.register_user_id(user_id=kwargs['from_user'])

    def update_chain(self):
        if len(self.block_chain.nodes) == 0:
            info = '{}\t{}'.format(self.get_format_time(), '节点列表为空,请先广播本节点以同步其他节点信息')
            self.append_output(info=info)
            return
        for node in self.block_chain.nodes:
            node = tuple(eval(node))
            info = '{}\t{}'.format(self.get_format_time(), '已向 节点{} 发送消息,请求同步最长链...'.format(node))
            self.append_output(info=info)
            MySocket.send_data(msg_type='UpdateChain', msg_data=self.ip_port, target_ip_port=node,
                               from_user=self.user_id)

    def send_chain(self, ip_port_from, *args, **kwargs):
        ip_port_from = tuple(ip_port_from)
        info = '{}\t{}'.format(self.get_format_time(), '发送当前链信息到 节点{}'.format(ip_port_from))
        self.append_output(info=info)
        MySocket.send_data(msg_type='ExistingChain', msg_data=self.block_chain.chain, target_ip_port=ip_port_from,
                           from_user=self.user_id)

    def replace_chain(self, new_chain, *args, **kwargs):
        if len(new_chain) <= len(self.block_chain.chain):
            self.append_output('{}\t{}'.format(self.get_format_time(), '接收到新链,但不是最长链,已舍弃'))
            return
        elif not self.block_chain.valid_chain(new_chain):
            self.append_output('{}\t{}'.format(self.get_format_time(), '接收到新链,但属于非法链,已舍弃'))
            return
        else:
            self.block_chain.chain = new_chain
            self.block_chain.currentTransaction.clear()
            self.append_output('{}\t{}'.format(self.get_format_time(), '接收到新链,比对验证无误,已替换'))

            _i, _j = self.get_balance_min_and_max()
            self.update_balance_min_and_max(_i, _j)

    def broadcast_last_transaction(self):
        info = '{}\t{}'.format(self.get_format_time(), '交易产生,已广播交易信息到网络...')
        self.append_output(info=info)
        MySocket.send_data(msg_type='NewTransaction', msg_data=self.block_chain.currentTransaction[-1],
                           target_ip_port=('<broadcast>', self.ip_port[1]), from_user=self.user_id)

    def add_transaction_from_net(self, transaction_info, *args, **kwargs):
        self.block_chain.new_transaction(
            sender=transaction_info['sender'],
            recipient=transaction_info['recipient'],
            amount=transaction_info['amount']
        )

        _i, _j = self.get_balance_min_and_max()
        self.update_balance_min_and_max(_i, _j)

        self.append_output('{}\t{}'.format(self.get_format_time(), '从其他节点接收到交易信息并添加到交易列表'))

    def send_chatting_message(self):
        msg = self.textEdit_chat.toPlainText()
        if msg == '':
            self.show_error_msg(title='Warning', msg='发送内容不能为空')
            return
        data = {'time': self.get_format_time(), 'msg': msg}
        MySocket.send_data(msg_type='ChatMessage', msg_data=data, target_ip_port=('<broadcast>', self.ip_port[1]),
                           from_user=self.user_id)
        self.textEdit_chat.setText('')
        self.show_chatting_message(data['time'], self.user_id, data['msg'])

    def show_chatting_message(self, msg_time, msg_user, msg_data):
        info = '{}\t{}\n\t{}'.format(msg_time, msg_user, msg_data)
        self.append_output(info=info)

    def receive_chatting_message(self, data, *args, **kwargs):
        # self.show_chatting_message(data['time'], kwargs['from_user'], data['msg'])
        self.signal_recv_msg.emit(data['time'], kwargs['from_user'], data['msg'])
        pass
Ejemplo n.º 16
0
from chain import Blockchain
from key import BitcoinAccount

wallet = BitcoinAccount()
address = wallet.to_address()
difficulty = 4

blockchain = Blockchain(difficulty)
blockchain.create_genesis_block()

print("blockchain: ")
print(blockchain.to_dict())

first_block = blockchain.blocks_list[-1]

print("First block: ")
print(first_block)

blockchain.add_transaction(address, "colas", 10)
blockchain.add_transaction(address, "salim", 30)
blockchain.mine_block()

print("blockchain: ")
print(blockchain.to_dict())
second_block = blockchain.blocks_list[-1]

print("Second block: ")
print(second_block)
Ejemplo n.º 17
0
from flask import Flask, request, render_template, redirect, url_for
from block import Block
from chain import Blockchain
from createTransations import writeTransactions
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

c = Blockchain()
making = False


@app.route('/', methods=['GET', 'POST'])
def index():
    if (request.method == 'POST'):
        i = request.form['blockReq']
        return redirect(url_for('blocks', index=i))
    return render_template('index.html', chainString=c.toRender)


@socketio.on('newBlock')
def newBlock():
    global making
    if (not making):
        making = True
        emit('makingBlock')
        pBlock = c.chain[-1]
        i = pBlock.index + 1
        ph = pBlock.id
Ejemplo n.º 18
0
import requests
from flask import Flask, request

from block import Block
from chain import Blockchain
from server_method import Server

server = Server()
# from server_method import Server
# from client_method import Client

app = Flask(__name__)

# the node's copy of blockchain
blockchain = Blockchain()
blockchain.create_genesis_block()

# the address to other participating members of the network
peers = set()


# endpoint to submit a new transaction. This will be used by
# our application to add new data (posts) to the blockchain
@app.route("/new_transaction", methods=["POST"])
def new_transaction():
    tx_data = request.get_json()
    required_fields = ["author", "content"]

    for field in required_fields:
        if not tx_data.get(field):
Ejemplo n.º 19
0
def create_chain():
    global blockchain
    blockchain = Blockchain(difficulty, address)
    blockchain.create_genesis_block()
    return "Success\n", 200
Ejemplo n.º 20
0
from flask import Flask, jsonify, request
from chain import Blockchain
from uuid import uuid4

app = Flask(__name__)

node_identifier = str(uuid4()).replace('-', '')
blockchain = Blockchain()  # Initializing blockchain


@app.route('/mine', methods=['GET'])
def mine():
    last_block = blockchain.last_block
    last_proof = last_block['proof']
    proof = blockchain.proof_of_work(last_proof)

    # rewarding the miner for his contribution. 0 specifies new coin has been mined
    blockchain.newTransaction(sender="0", recipient=node_identifier, amount=1)

    # now create the new block and add it to the chain
    previous_hash = blockchain.hash(last_block)
    block = blockchain.newBlock(proof, previous_hash)

    response = {
        'message': 'The new block has been forged',
        'index': block['index'],
        'transactions': block['transactions'],
        'proof': block['proof'],
        'previous_hash': block['previous_hash']
    }
import json

from chain import Blockchain
from key import BitcoinAccount

wallet = BitcoinAccount()
address = wallet.to_address()
difficulty = 4

blockchain = Blockchain(difficulty)
blockchain.create_genesis_block()

print("blockchain: ")
print(blockchain.to_dict())

first_block = blockchain.head

print("First block: ")
print(first_block)

blockchain.add_transaction(address, "colas", 10)
blockchain.add_transaction(address, "salim", 30)
blockchain.mine_block()

print("blockchain: ")
print(json.dumps(blockchain.to_dict(), indent=2))
second_block = blockchain.head

print("Second block: ")
print(second_block)
Ejemplo n.º 22
0
from uuid import uuid4
import json
from flask import Flask, jsonify, request
from chain import Blockchain

app = Flask(__name__)

node_identifier = str(uuid4()).replace('-', '')
node_miners_Key = 'NODE_KEY'  # The publicKey/Address of the Full Node that it uses to mine the transactions

blockchain = Blockchain()


@app.route('/mine', methods=['GET'])
def mine():
    last_block = blockchain.last_block

    proof = blockchain.mine_proof_of_work(last_block, 'miner_address')

    previous_hash = blockchain.hash(last_block)
    block = blockchain.add_block(proof, previous_hash)

    response = {
        "message": "Block is created",
        "index": block['index'],
        "transactions": block['transactions'],
        "proof": block['proof'],
        "previous_hash": block['previous_hash']
    }

    return jsonify(response), 200
Ejemplo n.º 23
0
from chain import Blockchain

difficulty = 4

blockchain =  Blockchain(difficulty)
blockchain.create_genesis_block()

print("blockchain: ")
print(blockchain.to_dict())

first_block = blockchain.blocks_list[0]

print("First block: ")
print(first_block)

blockchain.add_transaction("mohamed","colas", 10)
blockchain.add_transaction("mohamed","salim", 30)
blockchain.add_transaction("salim","colas", 10)
blockchain.mine_block()

print("blockchain: ")
print(blockchain.to_dict())
second_block = blockchain.blocks_list[-1]

print("Second block: ")
print(second_block)