Пример #1
0
    def test_discard_block(self):
        bc = BlockChain()

        cbtx = WalletHelper.generate_coinbase_with_unused_wallet()
        b = bc.new_block(cbtx)
        mine(b)
        self.assertTrue(bc.discard_block(b))

        b = Block(1337, bc.get_block_from_index(1).get_hash())
        cbtx = WalletHelper.generate_coinbase_with_unused_wallet()
        b.add_transaction(cbtx)
        mine(b)
        self.assertFalse(bc.discard_block(b))
        self.assertEqual(len(bc.chain), 2)

        b = Block(bc.get_block_from_index(-1).index, "obviously_fake_hash")
        cbtx = WalletHelper.generate_coinbase_with_unused_wallet()
        b.add_transaction(cbtx)
        mine(b)
        self.assertFalse(bc.discard_block(b))
        self.assertEqual(len(bc.chain), 2)

        b = Block(
            bc.get_block_from_index(1).index + 1,
            bc.get_block_from_index(1).get_hash())
        cbtx = WalletHelper.generate_coinbase_with_unused_wallet()
        b.add_transaction(cbtx)  # coinbase
        mine(b)
        self.assertTrue(bc.discard_block(b))
        self.assertEqual(len(bc.chain), 3)
Пример #2
0
    def __init__(self, parent):
        self.baseLvl = LevelConstructor(parent, 6, 3)
        self.canvas = self.baseLvl.getCanvas()
        self.blockWidth = self.baseLvl.getBlockWidth()

        self.blockBaseSettings = [self.canvas, self.blockWidth]

        self.block_0 = Block(self.blockBaseSettings,
                             size=2,
                             orientation="H",
                             position=[0, 2],
                             color="red",
                             isMain=True)
        self.block_2 = Block(self.blockBaseSettings,
                             size=3,
                             orientation="H",
                             position=[3, 5],
                             color="green")
        self.block_3 = Block(self.blockBaseSettings,
                             size=2,
                             orientation="H",
                             position=[4, 3],
                             color="lightBlue")
        self.block_4 = Block(self.blockBaseSettings,
                             size=3,
                             orientation="V",
                             position=[0, 3],
                             color="orange")
        self.block_5 = Block(self.blockBaseSettings,
                             size=3,
                             orientation="V",
                             position=[5, 0],
                             color="black")
        self.block_6 = Block(self.blockBaseSettings,
                             size=2,
                             orientation="V",
                             position=[3, 2],
                             color="blue")
        self.block_7 = Block(self.blockBaseSettings,
                             size=3,
                             orientation="V",
                             position=[2, 0],
                             color="purple")
        self.block_8 = Block(self.blockBaseSettings,
                             size=3,
                             orientation="H",
                             position=[3, 4],
                             color="maroon1")
        self.block_9 = Block(self.blockBaseSettings,
                             size=2,
                             orientation="H",
                             position=[0, 0],
                             color="navy")
        self.block_10 = Block(self.blockBaseSettings,
                              size=2,
                              orientation="H",
                              position=[3, 1],
                              color="grey")
Пример #3
0
    def __init__(self, pmax, nets_size, nodes_block_id):
        self.iteration = 1

        self.__blocks = [Block(pmax), Block(pmax)]
        self.__nets_distribution = [[0, 0]] * nets_size
        self.__nodes_locked = [False] * len(nodes_block_id)
        self.__nodes_gain = [0] * len(nodes_block_id)
        self.__nodes_block_id = nodes_block_id

        self.__best_partition = None
        self.cutsize = None
        self.prev_mincut = None
        self.mincut = None
 def __init__(self):
     super().__init__()
     for rec in self.db:
         self.blocks = []
         block = Block(rec['index'], rec['timestamp'], rec['hash'],
                       rec['previousHash'], rec['data'])
         self.blocks.append(block)
Пример #5
0
 def __init__(self, display: Surface):
     self.display = display
     self.score = Score(display)
     self.bullets = [Bullet(display) for _ in range(self.num_bullets)]
     self.block = Block(display,
                        (display.get_width() // 2 - Block.WIDTH // 2,
                         display.get_height() // 2 - Block.HEIGHT // 2),
                        self.bullets)
def get_next_block(previous_block):
    next_block = Block()
    next_block.index = previous_block.index + 1
    next_block.timestamp = datetime.now()
    next_block.data = "Block Number: " + str(next_block.index)
    next_block.hash = previous_block.generate_hash()
    next_block.previous_hash = previous_block.hash
    return  next_block
Пример #7
0
    def test_block_serialize(self):
        a = Block(0, 1, datetime.datetime.utcnow().timestamp())
        t1 = Transaction(0, 1, 2)
        a.add_transaction(t1)
        t2 = Transaction(0, 1, 2)
        a.add_transaction(t2)

        b = Block.from_json(a.to_json())
        self.assertEqual(a.get_hash(), b.get_hash())
Пример #8
0
 def new_block(self, proof, previous_hash=None):
     block = Block(index=len(self.block_chain) + 1,
                   proof=proof,
                   previous_hash=previous_hash
                   or hash_block(self.last_block),
                   transactions=self.current_transactions)
     self.block_chain.append(block)
     self.current_transactions = []
     return block
Пример #9
0
 def test_walk_transactions(self):
     b = Block(0, 0, 0)
     t = Transaction(0, 1, 2)
     b.add_transaction(t)
     self.assertEqual(len(list(b.get_transactions())), 1)
     t = Transaction(0, 1, 2)
     b.add_transaction(t)
     self.assertEqual(len(list(b.get_transactions())), 2)
     for x in b.get_transactions():
         self.assertIsInstance(x, Transaction)
Пример #10
0
def add_block():
    data = request.args.get("data")
    previous_block = block_chain.getlatestBlock()
    index = previous_block.index + 1
    time_stamp = str(datetime.datetime.now())
    previous_hash = previous_block.hash
    block = Block(index, time_stamp,
                  calculateHash(index, previous_hash, time_stamp, data),
                  previous_hash, data)
    block_chain.addBlock(block)
    return jsonify({"status": "Success"})
Пример #11
0
    def test_create_block(self):
        b = Block(0, 0, 0)
        self.assertIsInstance(b, Block)

        t = Transaction(0, 1, 2)

        self.assertTrue(b.add_transaction(t))

        header = b.get_header()
        header = json.loads(header)
        self.assertIsInstance(header, dict)
        self.assertIsInstance(header["trans_tree"], str)
Пример #12
0
def prepare_matrices():
    matrix_a = list()
    matrix_b = list()
    matrix_c = list()

    for i in range(MATRIXSIZE):
        a_row = list()
        b_row = list()
        c_row = list()

        matrix_a.append(a_row)
        matrix_b.append(b_row)
        matrix_c.append(c_row)

        for j in range(MATRIXSIZE):
            a_block = Block()
            b_block = Block()
            c_block = Block()

            a_row.append(a_block)
            b_row.append(b_block)
            c_row.append(c_block)

            a_block.make_persistent()
            b_block.make_persistent()
            c_block.make_persistent()

            a_block.initialize_random(BLOCKSIZE, BLOCKSIZE)
            b_block.initialize_random(BLOCKSIZE, BLOCKSIZE)
            c_block.initialize_zeros(BLOCKSIZE, BLOCKSIZE)

            if INPUT_IN_NVRAM:
                a_block.persist_to_nvram()
                b_block.persist_to_nvram()

            if EXEC_IN_NVRAM:
                c_block.persist_to_nvram()

    return matrix_a, matrix_b, matrix_c
Пример #13
0
    def _generate_descriptor_block(self):
        """
        Returns a Block instance of type TYPE_DESCRIPTOR.

        The current descriptor object is saved to it.

        Note: The next block ID field is redundant so it's given a constant 1.
        """
        return Block(block_id=0,
                     block_type=Block.TYPE_DESCRIPTOR,
                     data_length=len(self._descriptor.serialize()),
                     next_block_id=1,
                     data=self._descriptor.__dict__)
Пример #14
0
def create_chain_from_dump(chain_dump):
    bc = Blockchain()
    for idx, block_data in enumerate(chain_dump):
        block = Block(transactions=block_data["transactions"],
                      previous_hash=block_data["previous_hash"],
                      timestamp=block_data["timestamp"])
        proof = block_data['hash']
        if idx > 0:
            added = bc.add_block(block, proof)
            if not added:
                raise Exception("The chain dump is tampered!")
        else:  # the block is a genesis block, no verification needed
            bc.chain.append(block)
    return bc
Пример #15
0
    def _generate_data_termination_block(self, data="", block_id=None):
        """
        Returns a Block instance to be used as the last data block of a file.

        It closes the chain of data blocks by pointing to the superblock as
        next block.
        """
        new_block_id = block_id if block_id is not None else \
            self._get_next_available_block_id()
        return Block(block_id=new_block_id,
                     block_type=Block.TYPE_DATA,
                     data_length=len(data),
                     next_block_id=0,
                     data=data)
Пример #16
0
def prepare_matrices():
    matrix_a = list()
    matrix_b = list()
    matrix_c = list()

    for i in range(MATRIXSIZE):
        a_row = list()
        b_row = list()
        c_row = list()

        matrix_a.append(a_row)
        matrix_b.append(b_row)
        matrix_c.append(c_row)

        for j in range(MATRIXSIZE):
            a_block = Block()
            b_block = Block()
            c_block = Block()

            a_row.append(a_block)
            b_row.append(b_block)
            c_row.append(c_block)

            a_block.make_persistent()
            b_block.make_persistent()
            c_block.make_persistent()

            a_block.initialize_random(BLOCKSIZE, BLOCKSIZE)
            b_block.initialize_random(BLOCKSIZE, BLOCKSIZE)
            # c_block is not initialized, as the numpy matrix addition creates the structure

            if INPUT_IN_NVRAM:
                a_block.persist_to_nvram()
                b_block.persist_to_nvram()

    return matrix_a, matrix_b, matrix_c
Пример #17
0
    def __init__(self, vocab_size, emb_dim, pos_dim, n_blocks,
                    rnn, rnn_dim, n_rnn_layers, rnn_dropout, 
                    h_dim, n_heads, n_sub_layers_first,
                    n_sub_layers_second, device, dropout=0.1, emb_dropout=0.5,
                    self_loop=True, emb_matrix=None, topn=5):
        super().__init__()

        self.embedding = Embeddings(vocab_size, emb_dim, pos_dim, device, emb_dropout, emb_matrix, topn)
        
        self.in_dim = emb_dim + pos_dim
        self.rnn_dim = rnn_dim
        self.n_rnn_layers = n_rnn_layers
        self.rnn_dropout = nn.Dropout(rnn_dropout)
        self.device = device
        self.rnn = rnn
        self.n_blocks = n_blocks
        if rnn:
            self.fc_rnn = nn.Linear(self.in_dim, rnn_dim)
            self.rnn_eoncder = nn.LSTM(rnn_dim, rnn_dim, n_rnn_layers, 
                                        batch_first=True, dropout=rnn_dropout, bidirectional=True)

            self.in_dim = self.rnn_dim * 2
        
        self.fc = nn.Linear(self.in_dim, h_dim)
        self.dropout = nn.Dropout(dropout)
        self.blocks = nn.ModuleList()
        self.attention_guide_layer = MultiHeadAttentionLayer(h_dim, n_heads, dropout, device)
        for i in range(self.n_blocks):
            if i == 0:
                self.blocks.append(Block(h_dim, n_heads, n_sub_layers_first, n_sub_layers_second,
                                    device, None, dropout, self_loop))
            else:
                self.blocks.append(Block(h_dim, n_heads, n_sub_layers_first, n_sub_layers_second,
                                    device, self.attention_guide_layer, dropout, self_loop))

        self.aggregate_W = nn.Linear(2 * self.n_blocks * h_dim, h_dim)
Пример #18
0
def verify_and_add_block():
    """Endpoint to add a block mined by someone else to the node's chain. The node first verifies the block and then
    adds it to the chain."""

    block_data = request.get_json(force=True)

    block = Block(transactions=block_data["transactions"],
                  timestamp=block_data["timestamp"],
                  previous_hash=block_data["previous_hash"])
    proof = block_data['hash']
    added = blockchain.add_block(block, proof)

    if not added:
        return "The block was discarded by the node", 400

    return "Block added to the chain", 201
def initialize_database():
    print("Initializing database!")
    db = Base('block_chain.pdl')
    if (db.exists()):
        print("Delete block chain database")
        db.delete
    db.create('index',
              'timestamp',
              'hash',
              'previousHash',
              'data',
              mode="override")
    genesisData = "It all begins here!"
    timestamp = datetime.now()
    index = 0
    hash = calculateHash(index, "", timestamp, genesisData)
    genesisBlock = Block(index, str(timestamp), hash, None, genesisData)
    db.insert(genesisBlock.index, genesisBlock.timestamp, genesisBlock.hash,
              genesisBlock.previousHash, genesisBlock.data)
    db.commit()
Пример #20
0
    def test_import_transactions(self):
        b = Block(0, 0)
        w = Wallet()
        w.create_keys()
        t = Transaction(w.get_address(), 1, 1)
        w.sign_transaction(t)
        b.add_transaction(t)

        tp = TransactionPool()
        self.assertTrue(tp.import_transactions(b))
        self.assertEqual(len(tp), 1)

        t2 = tp.pull_transaction()
        self.assertEqual(t.get_hash(), t2.get_hash())

        # Importing unsigned transactions returns False
        tp = TransactionPool()
        t2 = Transaction(0, 1, 1)
        b.add_transaction(t2)
        self.assertFalse(tp.import_transactions(b))
Пример #21
0
def test_network(network):
    pygame.init()
    pygame.display.set_caption('Test')
    clock = pygame.time.Clock()
    surface = pygame.display.set_mode((surface_width, surface_height))
    bullets = [Bullet(surface) for _ in range(3)]
    score = 0
    score_font = pygame.font.SysFont("Arial", 30)
    block = Block(surface, (surface_width // 2, surface_height // 2),
                  bullets,
                  network=network)
    while True:
        surface.fill((0, 0, 0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit(0)

        block.predict()

        if block.is_alive:
            block.update()
            block.draw()
            score += 0.1

        for bullet in bullets:
            bullet.update()
            bullet.draw()

        if not block.is_alive:
            print(round(score))
            break

        text = score_font.render("Score: " + str(round(score)), True,
                                 (255, 255, 0))
        text_rect = text.get_rect()
        text_rect.center = (surface_width / 2, 100)
        surface.blit(text, text_rect)

        pygame.display.flip()
        clock.tick(200)
Пример #22
0
def verify_and_add_block():
    """Endpoint to add a block mined by someone else to the node's chain. The node first verifies the block and then
    adds it to the chain."""

    print("New block received from network...", sys.stdout)

    block_data = request.get_json(force=True)
    print(block_data, sys.stdout)
    block = Block(transactions=block_data["transactions"],
                  timestamp=block_data["timestamp"],
                  previous_hash=block_data["previous_hash"])
    block.block_hash = block_data["block_hash"]
    #TODO why are we generating the block hash once and then redefining it? Stupid.
    proof = block_data['block_hash']
    added = blockchain.add_block(block, proof)

    if not added:
        print("block discarded by node", sys.stdout)
        return "The block was discarded by the node", 400

    print("block added to chain", sys.stdout)
    return "Block added to the chain", 201
Пример #23
0
    def _create_data_blocks(self, data, terminating_at=None):
        """
        Writes a chain of data blocks to hold the given data.

        Optional terminating_at parameter defines the next_block_id of the last
        data block in the chain. If omitted, the chain ends at the superblock.
        """
        if len(data) == 0:
            return []
        chunks = list(split_string_by_max_size(data, self.max_block_size))
        new_block_ids = self._get_next_available_block_id(count=len(chunks))
        if isinstance(new_block_ids, int):
            new_block_ids = [new_block_ids]
        if terminating_at:
            new_block_ids.append(terminating_at)
        else:
            new_block_ids.append(
                self._get_next_available_block_id(count=1,
                                                  blacklist=new_block_ids))

        chunk = ""
        for chunk_id, chunk in zip(range(len(chunks)), chunks):
            new_block = Block(block_id=new_block_ids[chunk_id],
                              block_type=Block.TYPE_DATA,
                              data_length=len(chunk),
                              next_block_id=new_block_ids[chunk_id + 1],
                              data=chunk)
            bucket_id = calculate_bits_sum(chunk) % self._buckets_count
            self._write_block(bucket_id, None, new_block)

        if not terminating_at:
            new_block = self._generate_data_termination_block(
                block_id=new_block_ids[-1])
            bucket_id = calculate_bits_sum(chunk) % self._buckets_count
            self._write_block(bucket_id, None, new_block)
        return new_block_ids
Пример #24
0
 def __init__(self, chs=(1, 32, 64, 128, 256, 512)):
     super().__init__()
     self.enc_blocks = nn.ModuleList(
         [Block(chs[i], chs[i + 1]) for i in range(len(chs) - 1)])
     self.pool = nn.MaxPool2d(2)
Пример #25
0
 def test_block_mine(self):
     for i in range(1, 5):
         b = Block(0, 0, 0)
         mine(b)
         self.assertTrue(b.validate_proof())
def initialize_genesis_block():
    return Block(0, datetime.now(), "Genesis Bloc","0")
Пример #27
0
 def test_serialize(self):
     a = Block(0, 1, datetime.datetime.utcnow().timestamp())
     b = Block.from_json(a.to_json())
     self.assertEqual(a.get_hash(), b.get_hash())
Пример #28
0
def eval_genomes(genomes, config):
    # Init game
    pygame.init()
    pygame.display.set_caption('Blocky World Program')
    clock = pygame.time.Clock()
    surface = pygame.display.set_mode((surface_width, surface_height))
    bullets = [Bullet(surface) for _ in range(3)]
    generation_font = pygame.font.SysFont("Arial", 70)
    font = pygame.font.SysFont("Arial", 30)

    # Init NEAT
    blocks = list()

    for id, g in genomes:
        network = neat.nn.FeedForwardNetwork.create(g, config)
        g.fitness = 0

        # Init my cars
        x = random.gauss(surface_width // 2, 70)
        y = random.gauss(surface_height // 2, 50)
        blocks.append(Block(surface, (x, y), bullets, network=network))

    # Main loop
    global generation
    generation += 1
    while True:
        surface.fill((0, 0, 0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit(0)

        # Each block predicts next move
        for block in blocks:
            block.predict()

        # Update block and fitness
        remain_blocks = 0
        for i, block in enumerate(blocks):
            if block.is_alive:
                remain_blocks += 1
                block.update()
                genomes[i][1].fitness += 0.5

        for bullet in bullets:
            bullet.update()
            bullet.draw()

        # check
        if remain_blocks == 0:
            break

        # Drawing
        for block in blocks:
            if block.is_alive:
                block.draw()

        text = generation_font.render("Generation : " + str(generation), True,
                                      (255, 255, 0))
        text_rect = text.get_rect()
        text_rect.center = (surface_width / 2, 100)
        surface.blit(text, text_rect)

        text = font.render("remaining blocks : " + str(remain_blocks), True,
                           (255, 255, 0))
        text_rect = text.get_rect()
        text_rect.center = (surface_width / 2, 200)
        surface.blit(text, text_rect)

        pygame.display.flip()
        clock.tick(0)
Пример #29
0
def create_chain_from(chain_data):
    result = []
    for item in chain_data:
        result.append(Block(**item))
    print(result)
    return result