예제 #1
0
    async def test_difficulty_change(self):
        num_blocks = 30
        # Make it 5x faster than target time
        blocks = bt.get_consecutive_blocks(test_constants, num_blocks, [], 2)

        b: Blockchain = Blockchain(test_constants)
        await b.initialize({})
        for i in range(1, num_blocks):
            assert (await
                    b.receive_block(blocks[i]
                                    )) == ReceiveBlockResult.ADDED_TO_HEAD

        diff_25 = b.get_next_difficulty(blocks[24].header_hash)
        diff_26 = b.get_next_difficulty(blocks[25].header_hash)
        diff_27 = b.get_next_difficulty(blocks[26].header_hash)

        assert diff_26 == diff_25
        assert diff_27 > diff_26
        assert (diff_27 / diff_26) <= test_constants["DIFFICULTY_FACTOR"]

        assert (b.get_next_ips(
            blocks[1].header_hash)) == constants["VDF_IPS_STARTING"]
        assert (b.get_next_ips(blocks[24].header_hash)) == (b.get_next_ips(
            blocks[23].header_hash))
        assert (b.get_next_ips(blocks[25].header_hash)) == (b.get_next_ips(
            blocks[24].header_hash))
        assert (b.get_next_ips(blocks[26].header_hash)) > (b.get_next_ips(
            blocks[25].header_hash))
        assert (b.get_next_ips(blocks[27].header_hash)) == (b.get_next_ips(
            blocks[26].header_hash))
예제 #2
0
def main():
      
    path = os.getcwd()
    print(path)
    try:
        print('trying to read')
        os.chdir(path + '/blk')
        with open('blkchain.pkl', 'rb') as fp:
            chain = pickle.load(fp)
            fp.close()
    
    except:
        check = int(input("Are you miner or wallet :"))
        if check:
            print('Miner/Wallet started')
        else:

            print('Creating genesis')
            number_of_candidates = int(input("Enter number of candidates :"))
            trs = []
            for i in range(number_of_candidates):
                Name = input("Enter name :")
                age = input("Enter Age :")
                #usr = User(name=Name, age=age, publickey=sha256(Name.encode() + str(age).encode()).hexdigest(), privatekey=sha256(Name.encode() + str(age).encode()).hexdigest(), candidate=True)
                ts = Transaction(sha256(Name.encode() + str(age).encode()).hexdigest(), sha256(Name.encode() + str(age).encode()).hexdigest(), 0, name=Name)
                trs.append(ts)

            chain = Blockchain()
            chain.initialize_genesis(trs)
            os.mkdir('blk')
            os.chdir(path + '/blk')
            with open('blkchain.pkl', 'wb') as fp:
                pickle.dump(chain, fp)
                fp.close()
예제 #3
0
파일: test.py 프로젝트: nflaig/blockchain
 def setUp(self):
     self.blockchain = Blockchain()
     self.chain = self.blockchain.chain
     self.mempool = self.blockchain.mempool
     self.network = self.blockchain.network
     self.wallet = Wallet()
     self.initial_address = self.wallet.addresses[0]
예제 #4
0
    async def test_reorg_from_genesis(self):
        blocks = bt.get_consecutive_blocks(test_constants, 20, [], 9, b"0")
        store = FullNodeStore("fndb_test")
        await store._clear_database()
        b: Blockchain = Blockchain(store, test_constants)
        await b.initialize()
        for block in blocks:
            await b.receive_block(block)
        assert b.get_current_tips()[0].height == 20

        # Reorg from genesis
        blocks_reorg_chain = bt.get_consecutive_blocks(test_constants, 21,
                                                       [blocks[0]], 9, b"1")
        for reorg_block in blocks_reorg_chain:
            result = await b.receive_block(reorg_block)
            if reorg_block.height == 0:
                assert result == ReceiveBlockResult.ALREADY_HAVE_BLOCK
            elif reorg_block.height < 19:
                assert result == ReceiveBlockResult.ADDED_AS_ORPHAN
            else:
                assert result == ReceiveBlockResult.ADDED_TO_HEAD
        assert b.get_current_tips()[0].height == 21

        # Reorg back to original branch
        blocks_reorg_chain_2 = bt.get_consecutive_blocks(
            test_constants, 3, blocks, 9, b"3")
        await b.receive_block(blocks_reorg_chain_2[20]
                              ) == ReceiveBlockResult.ADDED_AS_ORPHAN
        assert (await b.receive_block(blocks_reorg_chain_2[21]
                                      )) == ReceiveBlockResult.ADDED_TO_HEAD
        assert (await b.receive_block(blocks_reorg_chain_2[22]
                                      )) == ReceiveBlockResult.ADDED_TO_HEAD
예제 #5
0
    async def test1(self):
        store = FullNodeStore("fndb_test")
        await store._clear_database()
        blocks = bt.get_consecutive_blocks(test_constants, 10, [], 10)
        b: Blockchain = Blockchain(test_constants)
        await store.add_block(blocks[0])
        await b.initialize({})
        for i in range(1, 9):
            assert (await
                    b.receive_block(blocks[i]
                                    )) == ReceiveBlockResult.ADDED_TO_HEAD
            await store.add_block(blocks[i])

        full_node_1 = FullNode(store, b)
        server_1 = ChiaServer(21234, full_node_1, NodeType.FULL_NODE)
        _ = await server_1.start_server("127.0.0.1", None)
        full_node_1._set_server(server_1)

        full_node_2 = FullNode(store, b)
        server_2 = ChiaServer(21235, full_node_2, NodeType.FULL_NODE)
        full_node_2._set_server(server_2)

        await server_2.start_client(PeerInfo("127.0.0.1", uint16(21234)), None)

        await asyncio.sleep(2)  # Allow connections to get made

        num_unfinished_blocks = 1000
        start_unf = time.time()
        for i in range(num_unfinished_blocks):
            msg = Message("unfinished_block",
                          peer_protocol.UnfinishedBlock(blocks[9]))
            server_1.push_message(
                OutboundMessage(NodeType.FULL_NODE, msg, Delivery.BROADCAST))

        # Send the whole block ast the end so we can detect when the node is done
        block_msg = Message("block", peer_protocol.Block(blocks[9]))
        server_1.push_message(
            OutboundMessage(NodeType.FULL_NODE, block_msg, Delivery.BROADCAST))

        while time.time() - start_unf < 300:
            if max([h.height for h in b.get_current_tips()]) == 9:
                print(
                    f"Time taken to process {num_unfinished_blocks} is {time.time() - start_unf}"
                )
                server_1.close_all()
                server_2.close_all()
                await server_1.await_closed()
                await server_2.await_closed()
                return
            await asyncio.sleep(0.1)

        server_1.close_all()
        server_2.close_all()
        await server_1.await_closed()
        await server_2.await_closed()
        raise Exception("Took too long to process blocks")
예제 #6
0
 async def test_get_header_hashes(self):
     blocks = bt.get_consecutive_blocks(test_constants, 5, [], 9, b"0")
     b: Blockchain = Blockchain(test_constants)
     await b.initialize({})
     for block in blocks:
         await b.receive_block(block)
     header_hashes = b.get_header_hashes(blocks[-1].header_hash)
     assert len(header_hashes) == 6
     print(header_hashes)
     print([block.header_hash for block in blocks])
     assert header_hashes == [block.header_hash for block in blocks]
예제 #7
0
 async def initial_blockchain(self):
     """
     Provides a list of 10 valid blocks, as well as a blockchain with 9 blocks added to it.
     """
     blocks = bt.get_consecutive_blocks(test_constants, 10, [], 10)
     b: Blockchain = Blockchain(test_constants)
     await b.initialize({})
     for i in range(1, 9):
         assert (await
                 b.receive_block(blocks[i]
                                 )) == ReceiveBlockResult.ADDED_TO_HEAD
     return (blocks, b)
예제 #8
0
 async def test_basic_blockchain(self):
     bc1: Blockchain = Blockchain()
     await bc1.initialize({})
     assert len(bc1.get_current_tips()) == 1
     genesis_block = bc1.get_current_tips()[0]
     assert genesis_block.height == 0
     assert genesis_block.challenge
     assert (bc1.get_header_blocks_by_height(
         [uint32(0)], genesis_block.header_hash))[0] == genesis_block
     assert (bc1.get_next_difficulty(
         genesis_block.header_hash)) == genesis_block.challenge.total_weight
     assert bc1.get_next_ips(genesis_block.header_hash) > 0
예제 #9
0
 async def test_get_header_hashes(self):
     blocks = bt.get_consecutive_blocks(test_constants, 5, [], 9, b"0")
     store = FullNodeStore("fndb_test")
     await store._clear_database()
     b: Blockchain = Blockchain(store, test_constants)
     await b.initialize()
     for block in blocks:
         await b.receive_block(block)
     header_hashes = b.get_header_hashes(blocks[-1].header_hash)
     assert len(header_hashes) == 6
     print(header_hashes)
     print([block.header_hash for block in blocks])
     assert header_hashes == [block.header_hash for block in blocks]
예제 #10
0
 async def test_basic_blockchain(self):
     store = FullNodeStore("fndb_test")
     await store._clear_database()
     bc1: Blockchain = Blockchain(store)
     await bc1.initialize()
     assert len(bc1.get_current_tips()) == 1
     genesis_block = bc1.get_current_tips()[0]
     assert genesis_block.height == 0
     assert genesis_block.challenge
     assert (bc1.get_header_blocks_by_height(
         [uint32(0)], genesis_block.header_hash))[0] == genesis_block
     assert (await bc1.get_next_difficulty(
         genesis_block.header_hash)) == genesis_block.challenge.total_weight
     assert await bc1.get_next_ips(genesis_block.header_hash) > 0
예제 #11
0
 async def initial_blockchain(self):
     """
     Provides a list of 10 valid blocks, as well as a blockchain with 9 blocks added to it.
     """
     store = FullNodeStore("fndb_test")
     await store._clear_database()
     blocks = bt.get_consecutive_blocks(test_constants, 10, [], 10)
     b: Blockchain = Blockchain(store, test_constants)
     await b.initialize()
     for i in range(1, 9):
         assert (await
                 b.receive_block(blocks[i]
                                 )) == ReceiveBlockResult.ADDED_TO_HEAD
     return (blocks, b)
예제 #12
0
    async def test2(self):
        num_blocks = 100
        store = FullNodeStore("fndb_test")
        await store._clear_database()
        blocks = bt.get_consecutive_blocks(test_constants, num_blocks, [], 10)
        b: Blockchain = Blockchain(test_constants)
        await store.add_block(blocks[0])
        await b.initialize({})

        full_node_1 = FullNode(store, b)
        server_1 = ChiaServer(21236, full_node_1, NodeType.FULL_NODE)
        _ = await server_1.start_server("127.0.0.1", None)
        full_node_1._set_server(server_1)

        full_node_2 = FullNode(store, b)
        server_2 = ChiaServer(21237, full_node_2, NodeType.FULL_NODE)
        full_node_2._set_server(server_2)

        await server_2.start_client(PeerInfo("127.0.0.1", uint16(21236)), None)

        await asyncio.sleep(2)  # Allow connections to get made

        start_unf = time.time()
        for i in range(1, num_blocks):
            msg = Message("block", peer_protocol.Block(blocks[i]))
            server_1.push_message(
                OutboundMessage(NodeType.FULL_NODE, msg, Delivery.BROADCAST))

        while time.time() - start_unf < 300:
            if max([h.height for h in b.get_current_tips()]) == num_blocks - 1:
                print(
                    f"Time taken to process {num_blocks} is {time.time() - start_unf}"
                )
                server_1.close_all()
                server_2.close_all()
                await server_1.await_closed()
                await server_2.await_closed()
                return
            await asyncio.sleep(0.1)

        server_1.close_all()
        server_2.close_all()
        await server_1.await_closed()
        await server_2.await_closed()
        raise Exception("Took too long to process blocks")
예제 #13
0
    async def test_basic_reorg(self):
        blocks = bt.get_consecutive_blocks(test_constants, 100, [], 9)
        b: Blockchain = Blockchain(test_constants)
        await b.initialize({})

        for block in blocks:
            await b.receive_block(block)
        assert b.get_current_tips()[0].height == 100

        blocks_reorg_chain = bt.get_consecutive_blocks(test_constants, 30,
                                                       blocks[:90], 9, b"1")
        for reorg_block in blocks_reorg_chain:
            result = await b.receive_block(reorg_block)
            if reorg_block.height < 90:
                assert result == ReceiveBlockResult.ALREADY_HAVE_BLOCK
            elif reorg_block.height < 99:
                assert result == ReceiveBlockResult.ADDED_AS_ORPHAN
            elif reorg_block.height >= 100:
                assert result == ReceiveBlockResult.ADDED_TO_HEAD
        assert b.get_current_tips()[0].height == 119
예제 #14
0
    async def test_lca(self):
        blocks = bt.get_consecutive_blocks(test_constants, 5, [], 9, b"0")
        b: Blockchain = Blockchain(test_constants)
        await b.initialize({})
        for block in blocks:
            await b.receive_block(block)

        assert b.lca_block == blocks[3].header_block
        block_5_2 = bt.get_consecutive_blocks(test_constants, 1, blocks[:5], 9,
                                              b"1")[5]
        block_5_3 = bt.get_consecutive_blocks(test_constants, 1, blocks[:5], 9,
                                              b"2")[5]

        await b.receive_block(block_5_2)
        assert b.lca_block == blocks[4].header_block
        await b.receive_block(block_5_3)
        assert b.lca_block == blocks[4].header_block

        reorg = bt.get_consecutive_blocks(test_constants, 6, [], 9, b"3")
        for block in reorg:
            await b.receive_block(block)
        assert b.lca_block == blocks[0].header_block
예제 #15
0
    async def test_lca(self):
        blocks = bt.get_consecutive_blocks(test_constants, 5, [], 9, b"0")
        store = FullNodeStore("fndb_test")
        await store._clear_database()
        b: Blockchain = Blockchain(store, test_constants)
        await b.initialize()
        for block in blocks:
            await b.receive_block(block)

        assert b.lca_block == blocks[3]
        block_5_2 = bt.get_consecutive_blocks(test_constants, 1, blocks[:5], 9,
                                              b"1")[5]
        block_5_3 = bt.get_consecutive_blocks(test_constants, 1, blocks[:5], 9,
                                              b"2")[5]

        await b.receive_block(block_5_2)
        assert b.lca_block == blocks[4]
        await b.receive_block(block_5_3)
        assert b.lca_block == blocks[4]

        reorg = bt.get_consecutive_blocks(test_constants, 6, [], 9, b"3")
        for block in reorg:
            await b.receive_block(block)
        assert b.lca_block == blocks[0]
예제 #16
0
parser.add_argument(
    '-o',
    type=str,
    help=
    'output file without requiring an initial blockchain file to read from (default: \'blockchain.json\')'
)

args = parser.parse_args()
node_id = uuid()

if __name__ == '__main__':
    # Load Blockchain File
    filename = args.file
    if filename:
        data = json.load(open(filename))
        blockchain = Blockchain(
            list(map(lambda block: block['header'], data['chain'])))
    else:
        filename = args.o
        blockchain = Blockchain()

    node = SPVNode(name=args.n or f'node-{node_id}',
                   port=args.p or 5000,
                   blockchain=blockchain)

    try:
        print(f'Starting node-{node_id}')

        # Establish Connection
        while not node.ready:
            node.send('version',
                      message=json.dumps(
예제 #17
0
파일: index.py 프로젝트: jutish/blockpy
from src.block import Block
from src.blockchain import Blockchain

# genesis = Block.getGenesis()
# bloque1 = Block.mine(genesis,'D4t4-Bloqu3_1')
# bloque2 = Block.mine(bloque1,'D4t4-Bloqu3_2')
# print(bloque1)
# print(bloque2)

print("Test 1 -Every blockchain has a Genesis Block")
blockchain = Blockchain()
genesis = blockchain.blocks[0]
print(genesis)

print("Test 2 - use addBlock")
blockchain = Blockchain()
data = 'd4t4-blk1'
blockchain.addBlock(data)
lastBlock = blockchain.blocks[-1]
print(lastBlock.data == data)
print(len(blockchain.blocks) == 2)

print("Test 3 - replaces the chain with a valid chain")
blockchain = Blockchain()
blockchainb = Blockchain()
data = 'd4t4-blk1'
blockchainb.addBlock(data)
blockchain.replaceBlock(blockchainb.blocks)
print(blockchain.blocks == blockchainb.blocks)

print("Test 4 - Does not replace with one with less blocks")
예제 #18
0
 def setUp(self):
     self.blockchain = Blockchain()
예제 #19
0
async def main():
    # Create the store (DB) and full node instance
    db_id = 0
    if "-id" in sys.argv:
        db_id = int(sys.argv[sys.argv.index("-id") + 1])
    store = FullNodeStore(f"fndb_{db_id}")

    blockchain = Blockchain(store)
    log.info("Initializing blockchain from disk")
    await blockchain.initialize()

    full_node = FullNode(store, blockchain)
    # Starts the full node server (which full nodes can connect to)
    host, port = parse_host_port(full_node)

    if full_node.config["enable_upnp"]:
        log.info(f"Attempting to enable UPnP (open up port {port})")
        try:
            upnp = miniupnpc.UPnP()
            upnp.discoverdelay = 5
            upnp.discover()
            upnp.selectigd()
            upnp.addportmapping(port, "TCP", upnp.lanaddr, port, "chia", "")
        except Exception as e:
            log.warning(f"UPnP failed: {e}")

    server = ChiaServer(port, full_node, NodeType.FULL_NODE)
    full_node._set_server(server)
    _ = await server.start_server(host, full_node._on_connect)
    wait_for_ui, ui_close_cb = None, None

    def master_close_cb():
        global server_closed
        if not server_closed:
            # Called by the UI, when node is closed, or when a signal is sent
            log.info("Closing all connections, and server...")
            full_node._shutdown()
            server.close_all()
            server_closed = True

    def signal_received():
        if ui_close_cb:
            ui_close_cb()
        master_close_cb()

    asyncio.get_running_loop().add_signal_handler(signal.SIGINT,
                                                  signal_received)
    asyncio.get_running_loop().add_signal_handler(signal.SIGTERM,
                                                  signal_received)

    if "-u" in sys.argv:
        # Starts the UI if -u is provided
        index = sys.argv.index("-u")
        ui_ssh_port = int(sys.argv[index + 1])
        from src.ui.prompt_ui import start_ssh_server

        wait_for_ui, ui_close_cb = await start_ssh_server(
            store,
            blockchain,
            server,
            port,
            ui_ssh_port,
            full_node.config["ssh_filename"],
            master_close_cb,
        )

    connect_to_farmer = "-f" in sys.argv
    connect_to_timelord = "-t" in sys.argv

    full_node._start_bg_tasks()

    log.info("Waiting to connect to some peers...")
    await asyncio.sleep(3)
    log.info(
        f"Connected to {len(server.global_connections.get_connections())} peers."
    )

    if connect_to_farmer and not server_closed:
        peer_info = PeerInfo(
            full_node.config["farmer_peer"]["host"],
            full_node.config["farmer_peer"]["port"],
        )
        _ = await server.start_client(peer_info, None)

    if connect_to_timelord and not server_closed:
        peer_info = PeerInfo(
            full_node.config["timelord_peer"]["host"],
            full_node.config["timelord_peer"]["port"],
        )
        _ = await server.start_client(peer_info, None)

    # Awaits for server and all connections to close
    await server.await_closed()

    # Awaits for all ui instances to close
    if wait_for_ui is not None:
        await wait_for_ui()
    await asyncio.get_running_loop().shutdown_asyncgens()
예제 #20
0
from fastapi import APIRouter

from src.blockchain import Blockchain
from src.model import NewBlock, Transaction

router = APIRouter()
bc = Blockchain()


@router.get("/last-block")
async def get_last_block():
    return bc.last_block


@router.post("/new-block")
async def new_block(block: NewBlock):
    return bc.new_block(block.proof, block.previous_hash)


@router.post("/transaction")
async def new_transaction(transaction: Transaction):
    return bc.new_transaction(transaction.sender, transaction.recipient,
                              transaction.amount)
예제 #21
0
from flask import Flask, jsonify, request
from flask_restful import reqparse, abort, Api, Resource
from src.blockchain import Blockchain

app = Flask(__name__)
api = Api(app)

blockchain = Blockchain('Alex')


class Get_Chain(Resource):
    def get(self):
        response = {'chain': blockchain.chain, 'length': len(blockchain.chain)}

        return response, 200


class Add_Transaction(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('sender', required=True, help='Obrigatório!')
        parser.add_argument('receiver', required=True, help='Obrigatório!')
        parser.add_argument('amount',
                            type=float,
                            required=True,
                            help='Obrigatório!')
        args = parser.parse_args()
        index = blockchain.add_transaction(args['sender'], args['receiver'],
                                           args['amount'])
        response = {
            'mensagem': f'Esta transação será adicionada ao bloco {index}'
예제 #22
0
def test_blockchain_constructor():
    test_temp_blockchain = Blockchain()
    assert len(test_temp_blockchain.chain) == 1
예제 #23
0
 def __init__(self):
     self.transactions = {}
     self.blockchain = Blockchain()
예제 #24
0
from flask import Flask, jsonify, request, redirect, url_for
from src.blockchain import Blockchain
from src.wallet import Wallet

app = Flask(__name__)

blockchain = Blockchain('bank')

@app.route('/add_transaction', methods=['POST'])
def add_transaction():
    json = request.get_json()
    transaction_keys = ['sender', 'receiver', 'amount']
    if not all(key in json for key in transaction_keys):
        return 'Está faltando algum elemento.', 400
    index = blockchain.add_transaction(json['sender'], json['receiver'], json['amount'])
    response = {'mensagem': f'Esta transação será adicionada ao bloco {index}'}
    return jsonify(response), 201

@app.route('/delete_transaction')
def delete_transaction():
    blockchain.delete_transaction()
    return jsonify({'mensagem':'Transação deletada!'})



@app.route('/mine_block/<hosting>', methods=['GET'])
def mine_block(hosting):
    w = Wallet()
    if not w.read_wallet(hosting):
        return jsonify({'mensagem':'Falta hosting wallet!'})
    blockchain.wallet = w
예제 #25
0
 def create_blockchain(self, first):
     self.blockchain = Blockchain(first=first)
예제 #26
0
parser.add_argument(
    '-o',
    type=str,
    help=
    'output file without requiring an initial blockchain file to read from (default: \'blockchain.json\')'
)

args = parser.parse_args()
node_id = uuid()

if __name__ == '__main__':
    # Load Blockchain File
    filename = args.file
    if filename:
        data = json.load(open(filename))
        blockchain = Blockchain(data['chain'], data['tx_info'])
    else:
        filename = args.o
        blockchain = Blockchain()

    node = MinerNode(name=args.n or f'node-{node_id}',
                     port=args.p or 5000,
                     blockchain=blockchain)

    try:
        print(f'Starting node-{node_id}')

        # Establish Connection
        while not node.ready:
            node.send('version',
                      message=json.dumps(
예제 #27
0
from time import time
from uuid import uuid4
from flask import Flask, jsonify, request
from src.blockchain import Blockchain
try:
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse

# instantiate our node
app = Flask(__name__)
# generate a globally unique adress for this node
node_identifier = str(uuid4()).replace('-', '')
cprint('> this node key: {}'.format(node_identifier), 'cyan')
# instantiate the blockchain
blockchain = Blockchain()


# define routes
@app.route('/mine', methods=['GET'])
def mine():
    # algorithm to get the next proof
    last_block = blockchain.last_block
    last_proof = last_block['proof']
    proof = blockchain.proof_of_work(last_proof)
    # we must recieve a reward for finding the proof
    # the sender is "0" to signify that this node has mined a new coin
    blockchain.new_transaction(sender="Mined",
                               recipient=node_identifier,
                               amount=1)
    # forge the new block by adding it to the chain
예제 #28
0
def test_blockchain(test_wallet_id):
    test_blockchain = Blockchain()
    test_blockchain.add_wallet(test_wallet_id)
    return test_blockchain