Esempio n. 1
0
    def create_block(cls):
        last_block = Block.last()
        previous_hash = last_block.block_id
        proof_of_work = ProofOfWork(previous_hash, 10)
        proof_result = proof_of_work.prove()

        if not proof_result.isValid():
            raise Exception('fail proof')

        transactions = UnconfirmedTransactionPool.transactions.copy()
        UnconfirmedTransactionPool.transactions.clear()
        block_number = len(Block.list()) + 1

        block = Block.build(
            block_number = block_number,
            version = "1",
            previous_block_hash = previous_hash,
            timestamp = datetime.now().timestamp(),
            merkle_root = "",  # TODO
            difficulty_target = 10,
            nonce = proof_result.nonce,
            transactions = transactions
        )

        for tx in transactions:
            tx.block_id = block.block_id

        Block.create_block(block)

        db.session.commit()

        transaction = cls._create_transaction_to_miner()

        return block, proof_result, transaction
Esempio n. 2
0
    def receive_block(cls, block, proof_result, send_node_url):
        last_block = Block.last()

        if not proof_result.isValid():
            raise Exception('received block is invalid')

        if last_block.block_id != block.previous_block_hash:
            if last_block.block_number < block.block_number:
                print('resolving conflicting...')
                cls._resolve_conflicts(send_node_url)

        if last_block.block_id == block.previous_block_hash:
            Block.create_block(block)

        UnconfirmedTransactionPool.transactions.clear()
        db.session.commit()