示例#1
0
def create_new_block_and_header():
    '''Creates a new block and header with the coinbase transaction included and returns them.'''
    block = blockchain.Block()
    header = blockchain.Header()
    # Create the coinbase Transaction
    coinbase_tx = blockchain.Transaction()
    coinbase_tx.setVersionNumber(
        len(Blockchain))  # Becomes a unique identifier for the transaction
    coinbase_tx.setInCounter(1)
    coinbase_tx.setOutCounter(1)
    coinbase_tx.setListOfInputs([blockchain.compute_double_hash('coinbase')])
    coinbase_tx.setListOfOutputs([blockchain.compute_double_hash('minerpay')])
    coinbase_tx.setTransactionHash(
        blockchain.computeTransactionHash(coinbase_tx))
    # Add to block and update header
    block.addTransaction(coinbase_tx)
    block.setTransactionCounter(block.getTransactionCounter() + 1)
    Tree = Merkel_Tree(list(block.getTransactions()[0].getTransactionHash()))
    Tree.construct_tree()
    header.sethashMerkleRoot(Tree.merkelroot)  # Set Merkel Root
    header.setTimestamp(int(time.time()))
    header.sethashPrevBlock(
        Blockchain[-1].getBlockhash())  # Set Previous Block
    header.setBits(0x1e200000)  # Set the difficulty bits
    block.setBlocksize(179)
    block.setBlockHeader(header)
    block.setBlockhash(blockchain.computeHeaderHash(block.getBlockHeader()))
    return block, header
示例#2
0
 def new_tx_from_data(self, data):
     phash = 0
     if len(self.unconfirmed_transactions) > 0:
         phash = self.unconfirmed_transactions[-1].hash
     tx = bl.Transaction(phash, data)
     self.unconfirmed_transactions.append(tx)
     return tx.serialize()
示例#3
0
def generate_genesis_block():
    '''Generates the genesis block'''
    # Genesis Transaction
    genesis_transaction = blockchain.Transaction()
    genesis_transaction.setVersionNumber(0)
    genesis_transaction.setOutCounter(1)
    genesis_transaction.setInCounter(1)
    genesis_transaction.setListOfInputs(['genin'])
    genesis_transaction.setListOfOutputs(['genesis07'])
    genesis_transaction.setTransactionHash(
        blockchain.computeTransactionHash(genesis_transaction))
    # Genesis Header
    genesis_header = blockchain.Header()
    genesis_header.sethashPrevBlock('0' * 64)  # Previous Hash of all 0's
    Tree = Merkel_Tree([genesis_transaction.getTransactionHash()])
    Tree.construct_tree()
    genesis_header.sethashMerkleRoot(Tree.merkelroot)
    # Genesis Block
    genesis_block = blockchain.Block()
    genesis_block.setBlockHeader(genesis_header)
    genesis_block.setTransactionCounter(1)
    genesis_block.addTransaction(genesis_transaction)
    genesis_block.setBlocksize(179)
    genesis_block.setBlockhash(
        blockchain.computeHeaderHash(genesis_block.getBlockHeader()))
    return genesis_block
示例#4
0
def new_transaction():
    if request.method == 'POST':
        tx_data = request.get_json()

        forwarder = tx_data['forwarder']
        receiver = tx_data['receiver']
        amount = tx_data['amount']
        publickey = tx_data['publickey']
        signature = tx_data['signature']
        hashed = tx_data['hash']

        transaction = blockchain.Transaction(forwarder, receiver, amount, publickey)
        print("Checking: " + str(transaction.overview()))
        if not has_transaction(transaction):
            # two step verification
            # transaction comes from publickey owner
            condition = crypto.verify(publickey, str(transaction), signature)
            print ('tx condition: ' + str(condition))
            # value can be spend
            # TODO get_balance(fingerprint)

            if condition:
                advertise_transaction(transaction)
                add_transaction(transaction)
                if not transaction_thread.is_alive():
                        transaction_thread = threading.Thread(name='transaction', target=process_transaction)
                    transaction_thread.start()
                return 'Transaction registered'
            else:
                return 'Verification fail, requester is a teapot', 418
        else:
            return 'Transaction already registered'
示例#5
0
    def test_tx_hash(self):
        inputs = [Bytes(b"one"), Bytes(b"two"), Bytes(b"three")]
        outputs = [Bytes(b"abc"), Bytes(b"xyz")]

        tx = blockchain.Transaction(inputs=inputs,
                                    outputs=outputs,
                                    hash_f=lambda x: b"(" + x + b")")

        assert b"(onetwothreeabcxyz\x00)" == tx.hash
示例#6
0
    def test_tx_bytes(self):
        inputs = [Bytes(b"one"), Bytes(b"two"), Bytes(b"three")]
        outputs = [Bytes(b"abc"), Bytes(b"xyz")]

        tx = blockchain.Transaction(inputs=inputs,
                                    outputs=outputs,
                                    hash_f=lambda x: x)

        assert b"onetwothreeabcxyz\x00" == tx.bytes
示例#7
0
    def test_tx_hash_with_extra_nonce(self):
        inputs = [Bytes(b"one"), Bytes(b"two"), Bytes(b"three")]
        outputs = [Bytes(b"abc"), Bytes(b"xyz")]

        tx = blockchain.Transaction(inputs=inputs,
                                    outputs=outputs,
                                    hash_f=lambda x: b"(" + x + b")")

        tx.extra_nonce = bytes_to_int(bytes("X".encode("utf-8")))

        assert b"(onetwothreeabcxyzX)" == tx.hash
示例#8
0
 def NewTransactionReceived(self, request, context):
     global TxnMemoryPool
     print("New Transaction Received")
     tr = blockchain.Transaction()
     tr.setVersionNumber(request.VersionNumber)
     tr.setInCounter(request.incounter)
     tr.setOutCounter(request.outcounter)
     tr.setListOfInputs(request.list_of_inputs)
     tr.setListOfOutputs(request.list_of_outputs)
     tr.setTransactionHash(request.transaction_hash)
     TxnMemoryPool.append(tr)  # Add the transaction to memory pool
     return response
示例#9
0
def transaction_from_serial(serial_data):
    '''
        Returns a python transaction from received serial data
        '''
    tx = blockchain.Transaction()
    tx.setVersionNumber(serial_data.VersionNumber)
    tx.setInCounter(serial_data.incounter)
    tx.setOutCounter(serial_data.outcounter)
    tx.setListOfInputs(serial_data.list_of_inputs)
    tx.setListOfOutputs(serial_data.list_of_outputs)
    tx.setTransactionHash(serial_data.transaction_hash)
    return tx
示例#10
0
def adv_tx(receiver, amount):
    global node
    global transaction_thread
    print(node.overview())
    t = blockchain.Transaction(node.fingerprint, receiver, amount, node.publickey)
    add_transaction(t)
    if not transaction_thread.is_alive():
        transaction_thread = threading.Thread(name='transaction', target=process_transaction)
        transaction_thread.start()
    for fingerprint, address in node.neighbours.items():
        a = 'http://' + address  + ':5000' + '/tx'
        r = requests.post(a, json=t.overview())
示例#11
0
 def add():
     tr = blockchain.Transaction()
     tr.setVersionNumber(1)
     tr.setInCounter(1)
     tr.setOutCounter(1)
     random_number = round(random.random(), 2)
     inp_value = str(round(time.time())) + str(random_number)
     tr.setListOfInputs([blockchain.compute_double_hash(inp_value)])
     tr.setListOfOutputs([
         blockchain.compute_double_hash(
             str(10 * random_number) + 'outputpay')
     ])
     tr.setTransactionHash(blockchain.computeTransactionHash(tr))
     TxnMemoryPool.append(tr)  # Add the transaction to memory pool
     newTransactionBroadcast(tr)
示例#12
0
    def create_coinbase_transaction(self, dest_key=None):
        """
        Creates a coinbase transaction. This transaction is included as the
        first transaction of the block and is creating a fixed amount of coins
        """

        coinbase_output = blockchain.TransactionOutput(
            amount=constants.BLOCK_COINBASE_AMOUNT,
            key=dest_key or self._ecdsa.public_key)

        coinbase_tx = blockchain.Transaction(
            inputs=[],
            outputs=[coinbase_output],
        )

        return coinbase_tx
示例#13
0
def new_block():
    global lock
    lock.acquire()
    if request.method == 'POST':
        tx_data = request.get_json()
        transactions.append(tx_data)

        index = tx_data['index']
        timestamp = tx_data['timestamp']
        previous_hash = tx_data['previous_hash']
        hashed = tx_data['hash']
        nonce = tx_data['nonce']
        miner = tx_data['miner']

        forwarder = tx_data['transaction']['forwarder']
        receiver = tx_data['transaction']['receiver']
        amount = tx_data['transaction']['amount']
        publickey = tx_data['transaction']['publickey']
        signature = tx_data['transaction']['signature']
        hashed = tx_data['transaction']['hash']

        transaction = blockchain.Transaction(forwarder, receiver, amount, publickey)
        print(blockchain.verify_proof(transaction, nonce, miner))
        print(crypto.verify(publickey, str(transaction), signature))
        # verify proof of work had place and transaction is from publickey owner
        condition = blockchain.verify_proof(transaction, nonce, miner) and \
                    crypto.verify(publickey, str(transaction), signature)

        if condition:
            advertise_block(block)
            #node.add_transaction(transaction)
            add_block(block)
            lock.release()
            return 'Transaction registered'
        else:
            return 'Verification fail, requester is a teapot', 418
    else:
        lock.release()