Ejemplo n.º 1
0
def mining():
    print("Into the mining process")
    # Initializing Election Class
    elec = Election()
    # Do not make a block if mempool is empty
    # if elec.redis_client.llen("mempool") == 0:
    #     print("No block made! Mempool is empty!")
    #     return
    # Transaction verification
    # Initializing Block Class
    blk = Block()
    # Create Coinbase Transaction
    blk.create_coinbase_transaction()
    # Connect to Previous Block
    blk.add_previous_block()
    # Scan Mempool
    vd = True
    for i in range(0, elec.redis_client.llen("mempool")):
        # Get Transaction
        tx = elec.redis_client.lindex('mempool', i).decode('utf-8')
        if tx == None:
            # Exit if tx is None
            break
        # Get tx verification verdict
        # verify_verdict = elec.verification.verify_tx(tx)
        # if verify_verdict == "verified":
        #     # Sending data to block
        #     blk.add_transaction(tx)
        # else:
        #     vd = False
        #     print("Some Transaction Verification Failed! Aborting Mining ...")
        #     break
    # If Tx Verification Fails
    if vd == False:
        print("Mining Aborted!")
        return
    # create block
    blk.compute_hash()
    blk.calculate_merkle_root()
    block = blk
    # add block
    blkChain = BlockChain()
    blkChain.add_block(block)
    print("Block added to this Node's blockchain!")
    # check
    # full Blockchain verify
    # full_verify_message = elec.verification.full_chain_verify()
    # if msg != "verified":
    #    return sync.chainsync()
    # if full_verify_message == "verified":
    # braodcast the block you made
    print("Broadcasting block made by this node ...")
    udphandler = UDPHandler()
    udphandler.sendblock(block.to_json())
Ejemplo n.º 2
0
    def final_addr_balance(self, addr):
        """ This function scans the complete blockchain and returns
        the total balance of an Address """
        chain_length = self.redis_client.llen('chain')
        total = 0
        used_transactions = set()
        while chain_length > 0:
            block = Block.from_json(
                json.loads(
                    self.redis_client.lindex('chain', chain_length -
                                             1).decode('utf-8')))
            for tx in block.transactions:
                for inp in tx.inputs:
                    if inp.address == addr:
                        used_transactions.add((inp.previous_tx, inp.index))
                for out_index, out in enumerate(tx.outputs):
                    if tx.hash not in used_transactions:
                        if out.address == addr:
                            total = total + out.value
                    else:
                        if out.address == addr and (
                                tx.hash, out_index) not in used_transactions:
                            total = total + out.value
            chain_length -= 1

        return total
Ejemplo n.º 3
0
    def test_merkle_root(self):
        block = Block()
        tx = Transaction()
        input = TransactionInput()
        input.address = "test_address"
        tx.add_input(input)
        tx.generate_hash()
        block.add_transaction(tx)
        block.calculate_merkle_root()
        initial_merkle_root = block.merkle_root

        tx1 = Transaction()
        input1 = TransactionInput()
        input1.address = "another_test_address"
        tx1.add_input(input1)
        tx1.generate_hash()
        block.add_transaction(tx1)
        block.calculate_merkle_root()
        final_merkle_root = block.merkle_root

        self.assertNotEqual(initial_merkle_root, final_merkle_root)
Ejemplo n.º 4
0
    def get_block_by_hash(self, hash: str) -> Block:
        chain_length = self.redis_client.llen('chain')
        while chain_length > 0:
            block = Block.from_json(
                json.loads(
                    self.redis_client.lindex('chain', chain_length -
                                             1).decode('utf-8')))
            if block.hash == hash:
                return block
            chain_length -= 1

        return
Ejemplo n.º 5
0
    def test_txs_by_address(self):
        blockchain = BlockChain()
        blockchain.flush_chain()
        block = Block()
        tx = Transaction()
        input1 = TransactionInput()
        input1.address = "test_address"
        tx.add_input(input1)
        tx.generate_hash()
        block.add_transaction(tx)

        tx1 = Transaction()
        output = TransactionOutput()
        output.address = "fake_address"
        output1 = TransactionOutput()
        output1.address = "test_address"
        tx1.add_output(output)
        tx1.add_output(output1)
        tx1.generate_hash()
        block.add_transaction(tx1)

        tx2 = Transaction()
        output2 = TransactionOutput()
        output2.address = "fake_address"
        tx2.add_output(output2)
        tx2.generate_hash()

        block.add_transaction(tx2)
        block.compute_hash()

        blockchain.add_block(block)
        txs = blockchain.get_txs_by_addr("test_address")
        getb = blockchain.get_block(-1)
        print(getb.to_json())
        for tx in txs:
            print(tx.hash, end='\n')

        # self.assertEqual(len(txs), 2)
        print(len(txs))
        blockchain.close()
Ejemplo n.º 6
0
    def get_tx_by_hash(self, hash: str):
        chain_length = self.redis_client.llen('chain')
        while chain_length > 0:
            block = Block.from_json(
                json.loads(
                    self.redis_client.lindex('chain', chain_length -
                                             1).decode('utf-8')))
            for tx in block.transactions:
                if tx.hash == hash:
                    return tx
            chain_length -= 1

        return
Ejemplo n.º 7
0
 def full_chain_verify(self):
     verify_message = "unverified"
     if self.chain_length == 0:
         return "Empty Chain! Verification failed!"
     for i in range(0, self.chain_length):
         raw = json.loads(self.redis_client.lindex('chain', i).decode('utf-8'))
         block = Block.from_json(raw)
         block.calculate_merkle_root()
         v_merkl_root = block.merkle_root
         if v_merkl_root != raw["merkle_root"]: 
             verify_message = "failed"
             self.del_from_faultblock(i)
             return verify_message
     verify_message = "verified"
     return verify_message
Ejemplo n.º 8
0
    def sendblock(self, request=None, response=None):
        """ Send block """

        if request is None and response is None:
            # If no data is being passed on by command handler
            pass
        if request is not None:
            # Processing requests
            UDPHandler.broadcastmessage(
                json.dumps({
                    "prev_command": "sendblock",
                    "body": request
                }))
        if response is not None:
            # Processing reaponse
            blkc = BlockChain()
            blkc.add_block(Block.from_json(response["body"]))
            blkc.close()
Ejemplo n.º 9
0
    def get_txs_by_addr(self, addr) -> List[Transaction]:
        txs = []
        chain_length = self.redis_client.llen('chain')
        while chain_length > 0:
            block = Block.from_json(
                json.loads(
                    self.redis_client.lindex('chain', chain_length -
                                             1).decode('utf-8')))
            print(len(block.transactions))
            for tx in block.transactions:
                inp_adresses = [inp.address for inp in tx.inputs]
                if addr in inp_adresses:
                    txs.append(tx)
                    continue
                out_adresses = [out.address for out in tx.outputs]
                if addr in out_adresses:
                    txs.append(tx)
                    continue
            chain_length -= 1

        return txs
Ejemplo n.º 10
0
    def get_utxos_by_addr(self, addr) -> List[Tuple[str, int, float]]:
        utxos = []
        chain_length = self.redis_client.llen('chain')
        used_transactions = set()
        while chain_length > 0:
            block = Block.from_json(
                json.loads(
                    self.redis_client.lindex('chain', chain_length -
                                             1).decode('utf-8')))
            for tx in block.transactions:
                for inp in tx.inputs:
                    if inp.address == addr:
                        used_transactions.add((inp.previous_tx, inp.index))
                for out_index, out in enumerate(tx.outputs):
                    if tx.hash not in used_transactions:
                        if out.address == addr:
                            utxos.append((tx.hash, out_index, out.value))
                    else:
                        if out.address == addr and (
                                tx.hash, out_index) not in used_transactions:
                            utxos.append((tx.hash, out_index, out.value))
            chain_length -= 1

        return utxos
Ejemplo n.º 11
0
from trucoin.Block import Block
from trucoin.Transaction import Transaction
from trucoin.TransactionInput import TransactionInput
from trucoin.TransactionOutput import TransactionOutput
import time
import sys
from utils import getsize, getbytes
output = TransactionOutput()
output.address = "1d3f347aada53547142da8edea5e0019e6ef31bb15"
output.n = 0
output.value = 50
transaction = Transaction()
transaction.add_output(output)
transaction.is_coinbase = True
transaction.hash = "eef9fda50a6bf6c11c5078d8772d94jk"
block = Block()
block.add_transaction(transaction)
block.calculate_merkle_root()
block.compute_hash()
block.miner = "1d3f347aada53547142da8edea5e0019e6ef31bb15jk"
block.size = getbytes(block)
print(block.__dict__)
message = {
    "hash": block.hash,
    "timestamp": block.timestamp,
    "transaction": block.transactions[0].broadcast_transaction(),
    "previous_block_hash": block.previous_block_hash,
    "merkle_root": block.merkle_root,
    "height": block.height,
    "miner": block.miner,
    "version": block.version,
Ejemplo n.º 12
0
 def __init__(self):
     blockchain = BlockChain()
     self.block = Block()
     self.redis_client = redis.Redis(host='localhost', port=6379, db=0)
     self.chain_length = self.redis_client.llen('chain')
Ejemplo n.º 13
0
    #         "outputs": [
    #             {
    #                 "value": 50,
    #                 "n": 0,
    #                 "address": addr
    #             }
    #         ],
    #         "hash": "eef9fda50a6bf6c11c5078d8772d94df4f60ce54573c009f145eb047426ad0fb",
    #         "block": "16e8dab3a9185d5329fac9cfdc0a81c7817826f701e747cb3751878061e4dc8c"
    #     }],
    #     "previous_block_hash": "",
    #     "merkle_root": "78bc90dcc3fe2ae1eca8b9d4e09b63653cd18f0b583e002b2b4d43cc09fca9cd",
    #     "height": 0,
    #     "version": "0.0.1",
    #     "size": 1949
    # }))

    for i in range(1):
        block = Block()
        block.add_previous_block()
        block.add_transaction(create_fake_transaction(
            global_addresses[random.randint(0, 9)]))
        block.create_coinbase_transaction()
        block.calculate_merkle_root()
        block.compute_hash()
        block.calcalute_block_size()
        redis_client.rpush("chain", json.dumps(block.to_json()))
        # print(block.to_json())
        udphandler = UDPHandler()
        udphandler.sendblock(block.to_json())
Ejemplo n.º 14
0
    def create_block(self):
        block = Block()
        block.create_coinbase_transaction()
        mempool = Mempool()
        blkc = BlockChain()

        mempool_size = mempool.get_len()
        if mempool_size == 0:
            return
        while mempool_size > 0:
            tx = mempool.get_transaction()
            block.add_transaction(tx)
            mempool_size -= 1
        
        block.calcalute_block_size()
        block.calculate_merkle_root()
        block.compute_hash()
        blkc.add_block(block)

        return block
Ejemplo n.º 15
0
 def get_block(self, index: int) -> Block:
     raw = self.redis_client.lindex("chain", index)
     if raw is not None:
         return Block.from_json(json.loads(raw.decode("utf-8")))
     else:
         return
Ejemplo n.º 16
0
 def add_block(self, blk: Block):
     self.redis_client.rpush('chain', json.dumps(blk.to_json()))