예제 #1
0
    def enter_any(self, prev_state):
        assert self.parent.interpreter.queue_size > 0, "Entered consensus state, but interpreter queue is empty!"

        # Merkle-ize transaction queue and create signed merkle hash
        all_tx = self.parent.interpreter.queue_binary
        self.log.info(
            "Delegate got tx from interpreter queue: {}".format(all_tx))
        self.merkle = MerkleTree(all_tx)
        self.merkle_hash = self.merkle.hash_of_nodes()
        self.log.info("Delegate got merkle hash {}".format(self.merkle_hash))
        self.signature = ED25519Wallet.sign(self.parent.signing_key,
                                            self.merkle_hash)

        # Create merkle signature message and publish it
        merkle_sig = MerkleSignature.create(sig_hex=self.signature,
                                            timestamp='now',
                                            sender=self.parent.verifying_key)
        self.log.info("Broadcasting signature {}".format(self.signature))
        self.parent.composer.send_pub_msg(
            filter=Constants.ZmqFilters.DelegateDelegate, message=merkle_sig)

        # Now that we've computed/composed the merkle tree hash, validate all our pending signatures
        for sig in [
                s for s in self.parent.pending_sigs if self.validate_sig(s)
        ]:
            self.signatures.append(sig)

        self.check_majority()
예제 #2
0
    def _build_valid_block_data(self, num_transactions=4) -> dict:
        """
        Utility method to build a dictionary with all the params needed to invoke store_block
        :param num_transactions:
        :return:
        """
        mn_sk = Constants.Testnet.Masternodes[0]['sk']
        mn_vk = ED25519Wallet.get_vk(mn_sk)
        timestamp = 9000

        raw_transactions = [build_test_transaction().serialize() for _ in range(num_transactions)]

        tree = MerkleTree(raw_transactions)
        merkle_leaves = tree.leaves_as_concat_hex_str
        merkle_root = tree.root_as_hex

        bc = build_test_contender(tree=tree)

        prev_block_hash = '0' * 64

        mn_sig = ED25519Wallet.sign(mn_sk, tree.root)

        return {
            'prev_block_hash': prev_block_hash,
            'block_contender': bc,
            'merkle_leaves': merkle_leaves,
            'merkle_root': merkle_root,
            'masternode_signature': mn_sig,
            'masternode_vk': mn_vk,
            'timestamp': timestamp
        }
예제 #3
0
    def test_valid_sender(self):
        # Confirm no error when correct public key is used
        msg = b'this is a pretend merkle tree hash'
        sk, vk = ED25519Wallet.new()
        signature = ED25519Wallet.sign(sk, msg)

        timestamp = 'now'
        MerkleSignature.create(sig_hex=signature,
                               timestamp=timestamp,
                               sender=vk)  # no error thrown
예제 #4
0
    def gather_consensus(self):
        self.log.debug("Starting consesnsus, with peers: {}"
                       .format(['{}:{}'.format(d['url'], d['port']) for d in self.delegates]))

        # if str(self.port)[-1] == '0':
        #     self.log.debug("Exiting consensus as I am not the chosen one")
        #     return

        # Get all tx
        tx = self.queue.dequeue_all()

        # Merkleize them and sign
        self.merkle = MerkleTree(tx)
        self.signature = ED25519Wallet.sign(self.signing_key, self.merkle.hash_of_nodes())
        self.signature = self.signature.encode()

        self.log.debug('signature is {}'.format(self.signature))

        # Time to gather from others
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        def get_message(connection):

            # DEBUG
            # if connection[-1] != '0':
            #     self.log.debug("Ignoring poke attempt, as he was not the chosen one")
            #     return
            # END DEBUG

            context = zmq.Context()
            request_socket = context.socket(socket_type=zmq.REQ)
            request_socket.connect(connection)

            self.log.warning("Poking url: {}".format(connection))
            
            poke = Poke.create()
            poke_msg = Message.create(Poke, poke.serialize())

            request_socket.send(poke_msg.serialize())

            self.log.warning("Waiting for poke reply...")
            msg = request_socket.recv()

            self.log.critical("Got reply from the poked delegate: {}".format(msg))

        connections = ['{}:{}'.format(d['url'], d['port']) for d in self.delegates]

        tasks = [loop.run_in_executor(None, get_message, connection) for connection in connections]

        loop.run_until_complete(asyncio.wait(tasks))

        self.log.critical("\nClosing event loop!\n")
        loop.close()
예제 #5
0
    def test_verify_wrong_ms(self):
        # Test merkle tree validation returns false for incorrect verifying (public) key
        msg = b'this is a pretend merkle tree hash'
        timestamp = 'now'
        sk, vk = ED25519Wallet.new()
        signature = ED25519Wallet.sign(sk, msg)
        ms = MerkleSignature.create(sig_hex=signature,
                                    timestamp=timestamp,
                                    sender=vk)

        sk1, vk1 = ED25519Wallet.new()

        self.assertFalse(ms.verify(msg, vk1))
예제 #6
0
def print_stuff():
    pprint(connection_list)

    print('\n===MERKLE TREE HASHED===')
    h = hashlib.sha3_256()
    [h.update(mm) for mm in m.nodes]
    print(h.digest().hex())

    print('\n===ENTIRE MERKLE TREE===')
    [print(mm.hex()) for mm in m.nodes]

    print('\n===SIGNATURE OF MERKLE HASH===')
    [print(ED25519Wallet.sign(k[0], h.digest())) for k in delegates]
예제 #7
0
    def test_deserialization_valid_json(self):
        # Test valid json throws no errors
        msg = b'this is a pretend merkle tree hash'
        sk, vk = ED25519Wallet.new()
        signature = ED25519Wallet.sign(sk, msg)

        d = {
            MerkleSignature.SIG: signature,
            MerkleSignature.TS: 'now',
            MerkleSignature.SENDER: vk
        }
        binary = json.dumps(d).encode()
        MerkleSignature.from_bytes(binary)
예제 #8
0
    def test_verify_valid_ms(self):
        """
        Tests that MerkleSignature.verify(...) returns true given a proper msg and vk
        """
        # Test merkle tree verify() validates correct verifying (public) keys
        msg = b'this is a pretend merkle tree hash'
        timestamp = 'now'
        sk, vk = ED25519Wallet.new()
        signature = ED25519Wallet.sign(sk, msg)
        ms = MerkleSignature.create(sig_hex=signature,
                                    timestamp=timestamp,
                                    sender=vk)

        self.assertTrue(ms.verify(msg))
예제 #9
0
    def _create_merkle_sig(self, msg: bytes):
        """
        Helper method to create a MerkleSignature and wallet keys
        :return: A tuple container (MerkleSignature, signing_key, verifying_key)
        """
        assert type(msg) == bytes, "Must pass in bytes"

        sk, vk = ED25519Wallet.new()
        signature = ED25519Wallet.sign(sk, msg)
        ms = MerkleSignature.create(sig_hex=signature,
                                    timestamp=TIMESTAMP,
                                    sender=vk)

        return ms, sk, vk
예제 #10
0
    def test_invalid_timestamp(self):
        """
        Test that if the timestamp field is not formatted as expected an error will be thrown
        """
        msg = b'this is a pretend merkle tree hash'
        sk, vk = ED25519Wallet.new()
        signature = ED25519Wallet.sign(sk, msg)

        timestamp = 99
        self.assertRaises(
            TypeError,
            MerkleSignature.create(sig_hex=signature,
                                   timestamp=timestamp,
                                   sender=vk))
예제 #11
0
    def test_invalid_sender_bad_hash(self):
        # Test an error is thrown when created with a sender of not valid hash
        msg = b'this is a pretend merkle tree hash'
        sk, vk = ED25519Wallet.new()
        signature = ED25519Wallet.sign(sk, msg)

        timestamp = 'now'
        vk_bad_hash = ''.join(
            'Z' for _ in range(64))  # verifying (public) key with bad hash
        self.assertRaises(
            Exception,
            MerkleSignature.create(sig_hex=signature,
                                   timestamp=timestamp,
                                   sender=vk_bad_hash,
                                   validate=False))
예제 #12
0
    def test_valid_creation(self):
        """
        Tests that a MerkleSignature created with some argument has the expected properties
        """
        msg = b'this is a pretend merkle tree hash'
        timestamp = 'now'
        sk, vk = ED25519Wallet.new()
        signature = ED25519Wallet.sign(sk, msg)
        ms = MerkleSignature.create(sig_hex=signature,
                                    timestamp=timestamp,
                                    sender=vk)

        self.assertEqual(ms.signature, signature)
        self.assertEqual(ms.timestamp, timestamp)
        self.assertEqual(ms.sender, vk)
예제 #13
0
    def test_invalid_sender_wrong_sender(self):
        """
        Tests that an error is raised during creation if an invalid sender field is passed in. A sender should be a
        64 character hex string verifying key.
        """
        # Test an error is thrown when MerkleSignature created with a sender that is not the correct public key
        msg = b'this is a pretend merkle tree hash'
        sk, vk = ED25519Wallet.new()
        signature = ED25519Wallet.sign(sk, msg)

        timestamp = 'now'
        vk_bad = ED25519Wallet.new()[1]  # different verifying (public) key
        bad_public_key = MerkleSignature.create(sig_hex=signature,
                                                timestamp=timestamp,
                                                sender=vk_bad)
        self.assertRaises(Exception, bad_public_key)
예제 #14
0
def build_test_merkle_sig(msg: bytes = b'some default payload',
                          sk=None,
                          vk=None) -> MerkleSignature:
    """
    Builds a 'test' merkle signature. Used exclusively for unit tests
    :return:
    """
    import time

    if not sk:
        sk, vk = ED25519Wallet.new()

    signature = ED25519Wallet.sign(sk, msg)

    return MerkleSignature.create(sig_hex=signature,
                                  timestamp=str(time.time()),
                                  sender=vk)
예제 #15
0
def create_std_tx(sender: tuple, recipient: tuple, amount: float):
    """
    Utility method to create signed transaction
    :param sender: A tuple containing the (signing_key, verifying_key) of the sender
    :param recipient: A tuple containing the (signing_key, verifying_key) of the recipient
    :param amount: The amount to send
    :return:
    """
    # TestNetTransaction.TX, sender, to, amount
    tx = {
        'payload': ('t', sender[1], recipient[1], str(amount)),
        'metadata': {}
    }
    tx["metadata"]["proof"] = SHA3POW.find(
        JSONSerializer.serialize(tx["payload"]))[0]
    # tx["metadata"]["signature"] = ED25519Wallet.sign(sender[0], json.dumps(tx["payload"]).encode())
    tx["metadata"]["signature"] = ED25519Wallet.sign(
        sender[0], JSONSerializer.serialize(tx['payload']))
    return tx
예제 #16
0
    def test_serialization(self):
        """
        Tests that a created block data reply successfully serializes and deserializes. The deserialized object should
        have the same properties as the original one before it was serialized.
        """
        msg = b'this is a pretend merkle tree hash'
        sk, vk = ED25519Wallet.new()
        signature = ED25519Wallet.sign(sk, msg)

        timestamp = 'now'
        valid_merkle_sig = MerkleSignature.create(sig_hex=signature,
                                                  timestamp=timestamp,
                                                  sender=vk)

        valid_merkle_sig_serialized = valid_merkle_sig.serialize()

        clone = MerkleSignature.from_bytes(valid_merkle_sig_serialized)

        self.assertEqual(valid_merkle_sig.signature, clone.signature)
        self.assertEqual(valid_merkle_sig.timestamp, clone.timestamp)
        self.assertEqual(valid_merkle_sig.sender, clone.sender)
예제 #17
0
파일: blocks.py 프로젝트: Mat001/cilantro
    def store_block(cls,
                    block_contender: BlockContender,
                    raw_transactions: List[bytes],
                    publisher_sk: str,
                    timestamp: int = 0):
        """

        Persist a new block to the blockchain, along with the raw transactions associated with the block. An exception
        will be raised if an error occurs either validating the new block data, or storing the block. Thus, it is
        recommended that this method is wrapped in a try block.

        :param block_contender: A BlockContender instance
        :param raw_transactions: A list of ordered raw transactions contained in the block
        :param publisher_sk: The signing key of the publisher (a Masternode) who is publishing the block
        :param timestamp: The time the block was published, in unix epoch time. If 0, time.time() is used
        :return: None
        :raises: An assertion error if invalid args are passed into this function, or a BlockStorageValidationException
         if validation fails on the attempted block

        TODO -- think really hard and make sure that this is 'collision proof' (extremely unlikely, but still possible)
        - could there be a hash collision in the Merkle tree nodes?
        - hash collision in block hash space?
        - hash collision in transaction space?
        """
        assert isinstance(
            block_contender, BlockContender
        ), "Expected block_contender arg to be BlockContender instance"
        assert is_valid_hex(
            publisher_sk,
            64), "Invalid signing key {}. Expected 64 char hex str".format(
                publisher_sk)

        if not timestamp:
            timestamp = int(time.time())

        tree = MerkleTree.from_raw_transactions(raw_transactions)

        publisher_vk = ED25519Wallet.get_vk(publisher_sk)
        publisher_sig = ED25519Wallet.sign(publisher_sk, tree.root)

        # Build and validate block_data
        block_data = {
            'block_contender': block_contender,
            'timestamp': timestamp,
            'merkle_root': tree.root_as_hex,
            'merkle_leaves': tree.leaves_as_concat_hex_str,
            'prev_block_hash': cls._get_latest_block_hash(),
            'masternode_signature': publisher_sig,
            'masternode_vk': publisher_vk,
        }
        cls._validate_block_data(block_data)

        # Compute block hash
        block_hash = cls._compute_block_hash(block_data)

        # Encode block data for serialization and finally persist the data
        log.info(
            "Attempting to persist new block with hash {}".format(block_hash))
        block_data = cls._encode_block(block_data)

        with DB() as db:
            # Store block
            res = db.tables.blocks.insert([{
                'hash': block_hash,
                **block_data
            }]).run(db.ex)
            if res:
                log.info(
                    "Successfully inserted new block with number {} and hash {}"
                    .format(res['last_row_id'], block_hash))
            else:
                log.error(
                    "Error inserting block! Got None/False result back from insert query. Result={}"
                    .format(res))
                return

            # Store raw transactions
            log.info(
                "Attempting to store {} raw transactions associated with block hash {}"
                .format(len(raw_transactions), block_hash))
            tx_rows = [{
                'hash': Hasher.hash(raw_tx),
                'data': encode_tx(raw_tx),
                'block_hash': block_hash
            } for raw_tx in raw_transactions]

            res = db.tables.transactions.insert(tx_rows).run(db.ex)
            if res:
                log.info("Successfully inserted {} transactions".format(
                    res['row_count']))
            else:
                log.error(
                    "Error inserting raw transactions! Got None from insert query. Result={}"
                    .format(res))