def test_replaceLedger(blockchain_three_blocks):
    blockchain = Blockchain()
    blockchain.replaceLedger(blockchain_three_blocks.ledger)

    assert blockchain.ledger == blockchain_three_blocks.ledger
def test_replaceLedgerBadLedger(blockchain_three_blocks):
    blockchain = Blockchain()
    blockchain_three_blocks.ledger[1].hash = 'bad_hash'

    with pytest.raises(Exception, match='cannot replace. The incoming chain is invalid:'):
        blockchain.replaceLedger(blockchain_three_blocks.ledger)
    blockMined = blockchain.ledger[-1]
    pubsub.broadcastBlock(blockMined)
    transactionPool.clearTransactionPool(blockchain.ledger)
    return jsonify(blockMined.toJson())
    #return render_template("blockchain_mine.html", blockmined=blockMined)


@app.route('/wallet/transact', methods=['POST'])
def route_Wallet_Transact():
    transactionData = request.get_json()
    transaction = transactionPool.existingTransaction(wallet.address)
    if not transaction:
        transaction = Transaction(wallet, transactionData['pollID'],
                                  transactionData['option'])
        pubsub.broadcastTransaction(transaction)
    return jsonify(transaction.toJson())
    #return render_template("wallet_transact", wallet_transact=transaction)


ROOT_PORT = 5000
PORT = ROOT_PORT
if os.environ.get('PEER') == 'True':
    PORT = random.randint(5001, 6000)
    result = requests.get(f'http://localhost:{ROOT_PORT}/blockchain')
    ledgerFromOtherNodes = (Blockchain.fromJson(result.json())).ledger
    try:
        blockchain.replaceLedger(ledgerFromOtherNodes)
    except Exception as e:
        print(f'exception in synchronising ledger {e}.')
print(PORT)
app.run(port=PORT)