示例#1
0
 def test_invalid_timestamp(self):
     data = {'message': 'this is the genesis block'}
     genesis_block = GenesisBlock(data)
     self.chain.append(genesis_block)
     data = {'message': 'this is a test'}
     next_block = genesis_block.next(data)
     next_block.timestamp = genesis_block.timestamp - 100
     with self.assertRaises(BlocksNotSequentialException):
         self.chain.append(next_block)
示例#2
0
 def test_invalid_index(self):
     data = {'message': 'this is the genesis block'}
     genesis_block = GenesisBlock(data)
     self.chain.append(genesis_block)
     data = {'message': 'this is a test'}
     next_block = genesis_block.next(data)
     next_block.timestamp = genesis_block.timestamp + 100
     genesis_block.index = 5
     with self.assertRaises(BlocksNotCorrelativeException):
         self.chain.append(next_block)
示例#3
0
 def test_invalid_hash(self):
     data = {'message': 'this is the genesis block'}
     genesis_block = GenesisBlock(data)
     self.chain.append(genesis_block)
     rogue_data = {'message': 'this is a different genesis block'}
     rogue_genesis_block = GenesisBlock(rogue_data)
     data = {'message': 'this is a test'}
     next_block = rogue_genesis_block.next(data)
     next_block.timestamp = genesis_block.timestamp + 100
     with self.assertRaises(BlockHashDontMatchException):
         self.chain.append(next_block)
示例#4
0
 def mine():
     if len(blockchain) == 0:
         genesis_block = GenesisBlock(miner_pub_key=miner_key)
         genesis_block.mine(blockchain.get_difficult())
         blockchain.add(genesis_block)
     else:
         block = Block(previous_block=blockchain.chain[-1], miner_pub_key=miner_key, \
             transactions=transactionPool.get_best_transactions(blockchain,1))
         block.mine(blockchain.get_difficult())
         blockchain.add(block)
     send_blockchain()
     return ''
示例#5
0
    def set_genesis(self, public_key, num_zeros, num_transactions):
        pk_bytes = bytes.fromhex(public_key)
        public_key = load_pem_public_key(pk_bytes, backend=default_backend())
        self.genesis_block = GenesisBlock(public_key, "", num_zeros,
                                          num_transactions + 1)
        logical_block = LogicalBlock("", 0, None, None)
        logical_block.block = self.genesis_block
        self.blockchain = [logical_block]
        self.blockheaders = []

        # wallet metadata on blockchain
        self.cur_coins_from_issuer = {}
        self.cur_coins_from_voter = {}

        self.pending_transactions = []

        self.interrupt_mining = 1
        self.issuer_id = public_key
        self.transactions_per_block = num_transactions
        self.mining_thread = None
        if self.mining_thread:
            self.mining_thread.terminate()  # BAD
        self.mining_thread = None
        self.is_mining = False
        self.mining_transactions = []
        self.recieved_new_block = False
示例#6
0
 def setUp(self):
     data = {
         'message': 'this is the genesis block'
     }
     self.genesis_block = GenesisBlock(data)
     service = Node(port=5559, genesis_block=self.genesis_block)
     threading.Thread(target=service.serve).start()
     self.node = service
     self.connect('localhost:5559')
示例#7
0
文件: client.py 项目: Edorka/blockpy
def block_from_data(source):
    index = source.get('index')
    if index == 0:
        return GenesisBlock(source.get('data'),
                            source.get('timestamp'))
    return Block(index,
                 source.get('previous_hash'),
                 source.get('data'),
                 source.get('timestamp'))
    def addGenesis(self):
        """
        Add genesis block the blockchain as the first block.

        - Create Genesis Block
        - Add it to the blockmap and set the chain graph.
        """
        self.primary_blockchain_block = GenesisBlock()
        self.blockmap[self.primary_blockchain_block.blockhash] = self.primary_blockchain_block
        self._chaingraph[self.primary_blockchain_block.blockhash] = set()
        self.max_height = 1
示例#9
0
 def test_peer_cant_import_different_network(self):
     new_block = self.genesis_block.next({"message": "second block"})
     node_a = self.nodes.get('a')
     node_a.chain.append(new_block)
     self.assertEqual(len(node_a.chain), 2)
     data = {'message': 'this is not the same genesis block'}
     rogue_genesis_work = GenesisBlock(data)
     node_c = self.create_node('c',
                               port=35558,
                               genesis_block=rogue_genesis_work,
                               peers=['localhost:35555'])
     self.assertEqual(len(node_c.peers), 1)
     self.assertEqual(len(node_c.chain), 1)
示例#10
0
 def test_adding_blocks(self):
     data = {'message': 'this is the genesis block'}
     genesis_block = GenesisBlock(data)
     data = {'message': 'this is a test'}
     self.chain.append(genesis_block)
     next_block = Block(1, "000", data)
     next_block.timestamp = genesis_block.timestamp + 100
     next_block.data = {'message': 'this is a modified genesis block'}
     with self.assertRaises(BlockHashDontMatchException):
         self.chain.append(next_block)
     next_block.previous_hash = genesis_block.hash
     self.chain.append(next_block)
     self.assertIn(next_block, self.chain)
     self.assertIn(genesis_block, self.chain)
示例#11
0
def blockchain():
    blockchain = Blockchain()

    private_keys = [43, 53, 63]
    public_keys = mapv(lambda priv: PrivateKey(priv).public_key().to_bytes(),
                       private_keys)

    genesis_block = GenesisBlock(miner_pub_key=public_keys[0])
    genesis_block.mine(blockchain.get_difficult())
    blockchain.add(genesis_block)

    miners = [public_keys[1], public_keys[2]]
    outputs_array = [[(public_keys[0], 1), (public_keys[1], 2)],
                     [(public_keys[2], 10), (public_keys[1], 1)]]

    for key, miner, outputs in zip(private_keys, miners, outputs_array):
        transaction = Wallet(key).sign(Transaction(outputs))
        block = Block(blockchain.get_last_block(), [transaction],
                      miner_pub_key=miner)
        block.mine(blockchain.get_difficult())
        blockchain.add(block)

    return blockchain
示例#12
0
    def __init__(self, label=None):

        # Labeling
        self.nodeType = "Basic"
        self.label = label

        (sk, pk) = generateKeyPair()
        self.privateKey = sk
        self.uncompressedPublicKey = pk

        cpk = compressPublicKey(pk)
        self.publicKey = cpk
        self.address = encode(cpk)

        self.peers = set()
        self.memPool = []
        self.blocks = {}

        # hardcode the first block into client nodes
        genesis = GenesisBlock()
        self.blocks[genesis.blockHeader.blockHash()] = genesis
示例#13
0
class PeersTestCase(unittest.TestCase, APIClient):
    def create_node(self, name, port=35555, genesis_block=None, peers=[]):
        if genesis_block is None:
            genesis_block = self.genesis_block
        if name in self.nodes:
            raise Exception('{} node already exists'.format(name))
        new_node = Node(port=port, peers=peers, genesis_block=genesis_block)
        self.nodes[name] = new_node
        threading.Thread(target=new_node.serve).start()
        return new_node

    def setUp(self):
        self.nodes = {}
        data = {'message': 'this is the genesis block'}
        self.genesis_block = GenesisBlock(data)
        self.create_node('a', port=35555)
        self.create_node('b', port=35556)

    def tearDown(self):
        peer_list = ','.join(self.nodes.keys())
        print('shutting down: {}'.format(peer_list))
        for name, node in self.nodes.items():
            node.shutdown()
            node.server_close()

    def test_peer_would_import_node_a(self):
        new_block = self.genesis_block.next({"message": "second block"})
        node_a = self.nodes.get('a')
        node_a.chain.append(new_block)
        node_c = self.create_node('c', port=35558, peers=['localhost:35555'])
        self.assertEqual(len(node_c.peers), 1)
        self.assertEqual(len(node_c.chain), 2)

    def test_peer_cant_import_different_network(self):
        new_block = self.genesis_block.next({"message": "second block"})
        node_a = self.nodes.get('a')
        node_a.chain.append(new_block)
        self.assertEqual(len(node_a.chain), 2)
        data = {'message': 'this is not the same genesis block'}
        rogue_genesis_work = GenesisBlock(data)
        node_c = self.create_node('c',
                                  port=35558,
                                  genesis_block=rogue_genesis_work,
                                  peers=['localhost:35555'])
        self.assertEqual(len(node_c.peers), 1)
        self.assertEqual(len(node_c.chain), 1)

    def test_peer_can_update_other_nodes(self):
        new_block = self.genesis_block.next({"message": "second block"})
        peers = ['localhost:35555', 'localhost:35556']
        node_c = self.create_node('c', port=35558, peers=peers)
        node_c.add_block(new_block, report=True)
        node_a = self.nodes.get('a')
        node_b = self.nodes.get('b')
        self.assertEqual(len(node_c.peers), 2)
        self.assertEqual(len(node_a.chain), 2)
        self.assertEqual(len(node_b.chain), 2)

    def test_peer_address_collision(self):
        import socket
        with self.assertRaises(socket.error):
            self.create_node('c', port=35555)

    def test_update_from_longest_chain(self):
        last = self.genesis_block
        node_a = self.nodes.get('a')
        node_b = self.nodes.get('b')
        for current in range(5):
            new_block = last.next({"message": "new block:{}".format(current)})
            if current < 4:
                node_a.add_block(new_block)
            node_b.add_block(new_block)
            last = new_block
        peers = ['localhost:35555', 'localhost:35556']
        node_c = self.create_node('c', port=35558, peers=peers)
        self.assertEqual(len(node_c.chain), 6)

    def test_do_not_update_from_discrepant(self):
        node_a = self.nodes.get('a')
        node_b = self.nodes.get('b')
        node_c = self.create_node('c', port=45557)
        node_d = self.create_node('d', port=45558)
        last = self.genesis_block
        for current in range(5):
            new_block = last.next({"message": "new block:{}".format(current)})
            node_b.add_block(new_block)
            node_c.add_block(new_block)
            node_d.add_block(new_block)
            if current < 4:
                node_a.add_block(new_block)
            else:
                rare_block = last.next(
                    {"message": "rare block:{}".format(current)})
                node_a.add_block(rare_block)
            last = new_block
        self.assertEqual(len(node_a.chain), 6)
        self.assertEqual(len(node_b.chain), 6)
        self.assertEqual(len(node_c.chain), 6)
        self.assertEqual(len(node_d.chain), 6)
        peers = [
            'localhost:35555', 'localhost:35556', 'localhost:45557',
            'localhost:45558'
        ]
        node_n = self.create_node('n', port=45559, peers=peers)
        self.assertEqual(len(node_n.peers), 4)
        self.assertEqual(len(node_n.chain), 6)
        last_node = node_n.chain.last()
        self.assertEqual(last_node.hash, last.hash)
示例#14
0
 def setUp(self):
     self.nodes = {}
     data = {'message': 'this is the genesis block'}
     self.genesis_block = GenesisBlock(data)
     self.create_node('a', port=35555)
     self.create_node('b', port=35556)
示例#15
0
文件: run.py 项目: Edorka/blockpy
from . import Node
from block import GenesisBlock
from os import environ

data = {'message': 'this is the genesis block'}
genesis_block = GenesisBlock(data)
try:
    port = int(environ.get('PORT', None))
except ValueError:
    port = 80
Node(port=port, genesis_block=genesis_block).serve()
示例#16
0
 def _genesis(self):
     block = GenesisBlock()
     self.accept_block(block)