Exemplo n.º 1
0
    def load_data(self):
        try:
            with open('blockchain.txt', mode='r') as f:
                # file_content = pickle.loads(f.read())
                file_content = f.readlines()
                #print(file_content)
                blockchain = json.loads(file_content[0][:-1])
                updated_blockchain = []
                for block in blockchain:
                    converted_tx = [
                        Transaction(tx['sender'], tx['recipient'],
                                    tx['amount'])
                        for tx in block['transaction']
                    ]
                    updated_block = Block(block['index'],
                                          block['previous_hash'], converted_tx,
                                          block['proof'], block['timestamp'])
                    updated_blockchain.append(updated_block)
                self.chain = updated_blockchain
                open_transaction = json.loads(file_content[1])
                updated_transactions = []
                for tx in open_transaction:
                    updated_transaction = Transaction(tx['sender'],
                                                      tx['recipient'],
                                                      tx['amount'])
                    updated_transactions.append(updated_transaction)
                self.open_transaction = updated_transactions

        except (IOError, IndexError):
            pass
        finally:
            print("cleanup!")
Exemplo n.º 2
0
    def load_data(self):

        try:

            with open('blockchain.txt', mode='r') as f:
        ##        file_content = pickle.loads(f.read())

                file_content = f.readlines()

        ##        blockchain = file_content['chain']
        ##        open_transactions = file_content['ot']
                blockchain = json.loads(file_content[0][:-1])
                updated_blockchain = []
                for block in blockchain:
                    # les blocks sont maintenant des objets block, et non plus des dictionnaires

                    converted_tx = [Transaction(tx['sender'],tx['recipient'],tx['amount']) for tx in block['transactions']]
                    updated_block = Block(block['index'], block['previous_hash'], converted_tx, block['proof'], block['timestamp'])
                    
                    updated_blockchain.append(updated_block)
                self.chain = updated_blockchain
                
                open_transactions = json.loads(file_content[1])

                updated_transactions = []
                for tx in open_transactions:
                    updated_transaction = Transaction(tx['sender'],tx['recipient'],tx['amount'])
                    updated_transactions.append(updated_transaction)     
                self.__open_transactions = updated_transactions
                
        except (IOError, IndexError):
            pass
        finally:
            print('Cleanup!')
Exemplo n.º 3
0
    def load_data(self):
        try:
            with open('blockchain.p', mode='rb') as file:
                data = pickle.loads(file.read())
                temp_chain = []
                for i in data['blockchain']:
                    block_obj = Block(i['index'], i['previous_hash'], [
                        Transaction(tx['_Transaction__sender'],
                                    tx['_Transaction__recipient'],
                                    tx['_Transaction__amount'])
                        for tx in i['transactions']
                    ], i['proof'], i['timestamp'])
                    temp_chain.append(block_obj)

                self.chain = temp_chain

                for i in data['open_txns']:
                    txn = Transaction(
                        i['_Transaction__sender'],
                        i['_Transaction__recipient'],
                        i['_Transaction__amount'],
                    )
                    self.__open_transactions.append(txn)
        except (IOError, EOFError):
            pass
Exemplo n.º 4
0
def main():

    genesis_transaction = Transaction("Logan", "Dorian", 3)

    # initialize genesis
    genesis_block = Block("wow you're cool if you find this message...",
                          genesis_transaction)

    second_transaction = Transaction("Terry", "Bob", 42)
    second_block = Block(genesis_block.hash, second_transaction)

    print(genesis_block.hash)
    print(second_block.hash)
Exemplo n.º 5
0
def parseTransactionsInAccount(account):
    account_transactions = []

    for transactions in account['data']:
        date_acquired = "-"
        date_sold = "-"
        if "buy" == transactions["type"]:
            date_acquired = transactions["updated_at"]
        elif "sell" == transactions["type"]:
            date_sold = transactions["updated_at"]
        else:
            continue
        description = transactions["details"]["title"]

        crypto_currency = transactions["amount"]["currency"]
        crypto_amount = transactions["amount"]["amount"]

        proceeds = transactions["native_amount"]["amount"]
        currency = transactions["native_amount"]["currency"]

        current_transaction = Transaction(description, crypto_currency, crypto_amount, date_acquired, date_sold, proceeds, currency)

        account_transactions.append(current_transaction)

    return account_transactions
def main():

    k_m = KeyManager()
    um = UTXOManager(k_m.my_address())

    i_k_m = KeyManager()
    u_k_m = KeyManager()

    t1 = CoinbaseTransaction(k_m.my_address())
    t2 = CoinbaseTransaction(k_m.my_address())
    t3 = CoinbaseTransaction(k_m.my_address())

    t4 = Transaction([TransactionInput(t1.to_dict(), 0)], [
        TransactionOutput(u_k_m.my_address(), 10.0),
        TransactionOutput(i_k_m.my_address(), 20.0)
    ])

    transactions = []
    transactions.append(t1.to_dict())
    transactions.append(t2.to_dict())
    transactions.append(t3.to_dict())
    transactions.append(t4.to_dict())

    um.extract_utxos(transactions)

    balance = um.my_balance

    print(balance)
Exemplo n.º 7
0
def mktx(nonce, gasprice, startgas, to, value, data):
    """Assemble an unsigned transaction.

    The result is the hex representation of the transaction in RLP encoding.
    """
    tx = Transaction(nonce, gasprice, startgas, to, value, str(data))
    click.echo(tx.hex_serialize(False))
Exemplo n.º 8
0
 async def commit_messages_from_backlog(self):
     """
     Validates a block send from the leader and appends it to the local blockchain.
     :return:
     """
     while not self._backlog.empty():
         message = self._backlog.get()
         term = message.get('term')
         broadcasted_message = json.loads(
             self.messages_to_save[message['uuid']]['data'])
         data = json.loads(message['data'])
         message_integrity = broadcasted_message == data
         if message_integrity:
             new_transaction = Transaction(
                 **json.loads(data['pending_messages'][0]))
             data['pending_messages'] = [new_transaction]
             new_block = Block(**data)
             self.blockchain.add_block(new_block)
             self.blockchain.save()
             await self.broadcast_to_clients({
                 'type': 'client_commit_confirm',
                 'source_term': term
             })
         else:
             await self.start_election()
Exemplo n.º 9
0
    def add_transaction(self, recipient, sender, amount = 1.0):
        """Append a new value as well as the last blockchain value to the blockchain
        
        Arguments:
            :Sender : the sender of the coins
            :Recipient : the recipient of the coins
            :Amount : the amount of coins sent (default = 1 coin)
            
            """
        
        #transaction = {
        #    'Sender': sender, 
        #    'Recipient': recipient, 
        #    'Amount': amount
        #}

        
        transaction = Transaction(sender, recipient, amount)
        
        if Verification.verify_transaction(transaction, self.get_balance):

            self.__open_transactions.append(transaction)
            self.save_data()
            return True
        return False
Exemplo n.º 10
0
    def __init__(self, data=None):

        if not data:
            return

        if re.match('^[0-9a-fA-F]*$', data):
            data = data.decode('hex')

        header, transaction_list, self.uncles = rlp.decode(data)
        [
            self.number, self.prevhash, self.uncles_root, self.coinbase,
            state_root, self.transactions_root, self.difficulty,
            self.timestamp, self.nonce, self.extra
        ] = header
        self.transactions = [Transaction(x) for x in transaction_list]
        self.state = Trie('statedb', state_root)
        self.reward = 0

        # Verifications
        if self.state.root != '' and self.state.db.get(self.state.root) == '':
            raise Exception("State Merkle root not found in database!")
        if bin_sha256(rlp.encode(transaction_list)) != self.transactions_root:
            raise Exception("Transaction list root hash does not match!")
        if bin_sha256(rlp.encode(self.uncles)) != self.uncles_root:
            raise Exception("Uncle root hash does not match!")
Exemplo n.º 11
0
def trans_generator(env):
    '''
    1. Generates transaction in a random time derived from Mean Transaction generation time and its 
    Standard Deviation.
    2. Assigns the transaction to a node radomly from the list of transactions.
    '''
    # Use a global ID for transaction
    global txID
    txID = 2300
    while True:
        # Generate random transaction size and gas
        TX_SIZE = random.gauss(config['mean_tx_size'], config['sd_tx_size'])
        TX_GAS = random.gauss(config['mean_tx_gas'], config['sd_tx_gas'])

        txID += 1
        transaction = Transaction(TX_GAS, TX_SIZE, txID)
        # Choose a node randomly from the nodelist
        #node = random.choice(nodelist)
        # choose a node manually
        node = 100
        # select a sealer

        # Assign the task to the node; Find the node object with the nodeID
        for i in node_map:
            if i.nodeID == node:
                #print("%d, %d, Appended, Transaction, %d"%(env.now,i.nodeID,txID))
                logger.debug("%d, %d,Appended, Transaction, %d" %
                             (env.now, i.nodeID, txID))
                i.add_transaction(transaction)
        yield env.timeout(
            random.gauss(config['mean_tx_generation'],
                         config['sd_tx_generation']))
Exemplo n.º 12
0
    def resolve(self):
        winner_chain = self.chain
        replace = False
        for node in self.__peer_nodes:
            url = "http://{}/chain".format(node)
            try:
                response = requests.get(url)
                node_chain = response.json()
                node_chain = [JBlock(block["index"], block["previous_hash"],
                                     [Transaction(transaction["sender"], transaction["recipient"], transaction["signature"], transaction["amount"]) for transaction in block["transactions"]],
                                     block["proof"], block["timestamp"]) for block in node_chain]

                node_chain_lenght = len(node_chain)
                local_chain_lenght = len(self.chain)
                if node_chain_lenght > local_chain_lenght and Verification.validate_j_chain(node_chain):
                    winner_chain = node_chain
                    replace = True
            except requests.exceptions.ConnectionError:
                continue
        self.resolve_conflicts = False
        self.chain = winner_chain
        if replace:
            self.open_transactions = []
        FileHandler.save_j_chain(self)
        return replace
Exemplo n.º 13
0
 def add_transaction(self, sender, recipient, signature, amount, broadcast=False):
     # if self.node is None:
     #     return False
     transaction = Transaction(sender, recipient, signature, amount)
     if Wallet.verify_signture(transaction):
         if Verification.verify_transaction(transaction, sender, self.get_balance):
             self.open_transactions.append(transaction)
             FileHandler.save_j_chain(self)
             if not broadcast:
                 for node in self.__peer_nodes:
                     url = "http://{}/broadcast-transaction".format(node)
                     try:
                         response = requests.post(url, json={"sender":sender, "recipient":recipient, "amount":amount, "signature":signature})
                         if response.status_code == 400 or response.status_code == 500:
                             print("Transaction declined, needs resolving")
                             return False
                     except requests.exceptions.ConnectionError:
                         continue
                 return True
         else:
             print("This Transaction is not possible, as it exceeds your balance!")
             return False
     else:
         print("The Signature of this transaction is not valid")
         return False
     return True
Exemplo n.º 14
0
    def mine_block(self):
        if self.node is None:
            return None

        last_block = self.get_last_entry()

        hash_value = hash_util.hash_block(last_block)
        proof = self.proof_of_work(hash_value)

        mining_transaction = Transaction("MINING", self.node, "", self.MINING_REWARD)
        self.open_transactions.append(mining_transaction)

        block = JBlock(len(self.chain), hash_value, self.open_transactions, proof)
        if self.transaction_signature_is_valid(block):
            self.__chain.append(block)
            self.open_transactions = []
            FileHandler.save_j_chain(self)
            for node in self.__peer_nodes:
                url = "http://{}/broadcast-block".format(node)
                try:
                    converted_block = block.__dict__.copy()
                    converted_block["transactions"] = [transaction.__dict__ for transaction in converted_block["transactions"]]
                    response = requests.post(url, json={"block": converted_block})
                    if response.status_code == 400 or response.status_code == 500:
                        print("block declined, needs resolving")
                    if response.status_code == 409:
                        self.resolve_conflicts = True
                except requests.exceptions.ConnectionError:
                    continue
            return block
        else:
            print("Fehler: Die Transactionen wurden geändert")
            return None
Exemplo n.º 15
0
    def new_transaction(self, sender, recipient, energy_amount, price, bid_type, electric_hash):
        """
        Creates a new transaction to go into the next mined Block

        :param sender: Address of the Sender
        :param recipient: Address of the Recipient
        :param amount: Amount
        :return: The index of the Block that will hold this transaction
        """

        tr = Transaction(bid_id=len(self.current_transactions),   # this may be repeated but it is only used to print
                         seller_id=sender, buyer_id=recipient, energy_amount=energy_amount,
                         price=price, bid_type=bid_type, bid_hash=electric_hash)

        # self.current_transactions.append({
        #     'sender': sender,
        #     'recipient': recipient,
        #     'energy_amount': energy_amount,
        #     'price': price,
        #     'bid_type': bid_type,
        #     'electric_hash': electric_hash
        # })

        self.current_transactions.append(tr)

        return self.last_block['index'] + 1
Exemplo n.º 16
0
    def new_transaction(self, from_addr, to_addr, amount, fee):
        inputs = []
        outputs = []
        ifname = 'ens33'  # enp2s0
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        ip = socket.inet_ntoa(
            fcntl.ioctl(s.fileno(), 0x8915,
                        struct.pack('256s', bytes(ifname[:15],
                                                  'utf-8')))[20:24])

        wallets = Wallets()
        from_wallet = wallets[from_addr]
        pub_key = from_wallet.public_key

        acc, valid_outpus = self._find_spendable_outputs(from_addr, amount)
        # if acc < amount + fee:  # change
        # raise NotEnoughAmountError(u'not enough coin')
        for fout in valid_outpus:
            index = fout.index
            txid = fout.txid
            input = TXInput(txid, index, pub_key)
            inputs.append(input)

        output = TXOutput(amount, to_addr)
        outputs.append(output)
        if acc > amount + fee:  # change
            # a change
            outputs.append(TXOutput(acc - amount - fee, from_addr))  # change

        tx = Transaction(inputs, outputs, fee, ip)  # change
        tx.set_id()
        self.sign_transaction(tx, from_wallet.private_key)
        return tx
Exemplo n.º 17
0
def receive(obj):
    d = rlp.decode(obj)
    # Is transaction
    if len(d) == 8:
        tx = Transaction(obj)
        if mainblk.get_balance(tx.sender) < tx.value + tx.fee: return
        if mainblk.get_nonce(tx.sender) != tx.nonce: return
        txpool[bin_sha256(blk)] = blk
        broadcast(blk)
    # Is message
    elif len(d) == 2:
        if d[0] == 'getobj':
            try:
                return db.Get(d[1][0])
            except:
                try:
                    return mainblk.state.db.get(d[1][0])
                except:
                    return None
        elif d[0] == 'getbalance':
            try:
                return mainblk.state.get_balance(d[1][0])
            except:
                return None
        elif d[0] == 'getcontractroot':
            try:
                return mainblk.state.get_contract(d[1][0]).root
            except:
                return None
        elif d[0] == 'getcontractsize':
            try:
                return mainblk.state.get_contract(d[1][0]).get_size()
            except:
                return None
        elif d[0] == 'getcontractstate':
            try:
                return mainblk.state.get_contract(d[1][0]).get(d[1][1])
            except:
                return None
    # Is block
    elif len(d) == 3:
        blk = Block(obj)
        p = block.prevhash
        try:
            parent = Block(db.Get(p))
        except:
            return
        uncles = block.uncles
        for s in uncles:
            try:
                sib = db.Get(s)
            except:
                return
        processblock.eval(parent, blk.transactions, blk.timestamp,
                          blk.coinbase)
        if parent.state.root != blk.state.root: return
        if parent.difficulty != blk.difficulty: return
        if parent.number != blk.number: return
        db.Put(blk.hash(), blk.serialize())
Exemplo n.º 18
0
    def createTransaction(self, sender, recipient, amount):
        """ Creates a transaction to go into the next block """
        transaction = Transaction(sender, recipient, amount)

        if transaction.validate():
            self.__currentTransactionsList.append(transaction)
            return transaction, True
        return None, False
Exemplo n.º 19
0
 def generateGenesisBlock(self):
     transaction_0 = Transaction(type='Root',
                                 timestamp=self.get_time(),
                                 message='Genesis Block')
     local_transaction = [transaction_0]
     genesis = Block(0, self.get_time(), local_transaction, 0, 0)
     genesis.hash = '000'
     return genesis
Exemplo n.º 20
0
    def load_data(j_chain, open_transactions, peer_nodes, port):
        try:
            with open("blockchain-{}.txt".format(port), mode="r") as f:
                file_content = f.readlines()
                blockchain = json.loads(file_content[0][:-1])
                updated_j_chain = []
                for block in blockchain:
                    previous_hash = block["previous_hash"]
                    index = block["index"]
                    proof = block["proof"]
                    timestamp = block["timestamp"]
                    transactions = [
                        Transaction(transaction["sender"],
                                    transaction["recipient"],
                                    transaction["signature"],
                                    transaction["amount"])
                        for transaction in block["transactions"]
                    ]

                    updated_block = JBlock(index, previous_hash, transactions,
                                           proof, timestamp)
                    updated_j_chain.append(updated_block)

                open_transactions = json.loads(file_content[1][:-1])
                updated_transactions = []
                for transaction in open_transactions:
                    updated_transaction = Transaction(transaction["sender"],
                                                      transaction["recipient"],
                                                      transaction["signature"],
                                                      transaction["amount"])
                    updated_transactions.append(updated_transaction)

                j_chain = updated_j_chain
                open_transactions = updated_transactions
                peer_nodes = set(json.loads(file_content[2]))

        except (IOError, IndexError):
            print("File not found: Make file")
            f = open("blockchain-{}.txt".format(port), mode="w+")
            f.close()

        return j_chain, open_transactions, peer_nodes
Exemplo n.º 21
0
def quicktx(client, gasprice, startgas, to, value, data, key):
    """Create and finalize a transaction.

    This command is a shortcut that chains getnonce, mktx, signtx, and applytx.
    It returns the server's response.
    """
    encoded_key = encode_privkey(key, 'hex')
    nonce = int(client.getaccount(utils.privtoaddr(encoded_key))['nonce'])
    tx = Transaction(nonce, gasprice, startgas, to, value, str(data))
    tx.sign(encode_privkey(key, 'hex'))
    pecho(client.applytx(tx))
Exemplo n.º 22
0
    def test_signing_simple_transaction(self):
        inputs = [
            ('b0ff74bb0dd894797153ccb862c9f9a488e657452647ada440fe1006ece95c78', 0),
        ]

        outputs = [
            ('115MDLurYMiExVwfTU7R4kE43zrdVoC2pz', 50000000),
        ]

        tx = Transaction(inputs, outputs)
        txCopy = tx.generate_signing_form(0, self.key)
Exemplo n.º 23
0
    def setUp(self):
        inputs = [
            ('b0ff74bb0dd894797153ccb862c9f9a488e657452647ada440fe1006ece95c78', 0),
            ('683d180645632d45f23baf2fb2897241321c1af779f3064ebd24aa517bae6a22', 0),
        ]

        outputs = [
            ('1EL3y9j8rzZwa8Hxmx2scatb3bh8KKFK6v', 1000),
            ('115MDLurYMiExVwfTU7R4kE43zrdVoC2pz', 49585000),
        ]

        self.tx = Transaction(inputs, outputs)
Exemplo n.º 24
0
 def getpending(self):
     """Request a list of pending transactions."""
     response = self.request('/pending/')['transactions']
     print response
     txs = []
     for tx_dict in response:
         txs.append(
             Transaction(int(tx_dict['nonce']), int(tx_dict['gasprice']),
                         int(tx_dict['startgas']), tx_dict['to'],
                         int(tx_dict['value']), tx_dict['data'][2:],
                         int(tx_dict['v']), int(tx_dict['r']),
                         int(tx_dict['s'])))
     return txs
Exemplo n.º 25
0
 def init_dcp(self, addr):
     nonce = self.miner.block.get_nonce(
         self_addr)  #self.config.get('wallet', 'coinbase'))
     print 'init nonce for dcp', nonce
     GASPRICE = 100
     print 'addr!'
     print addr
     new_dcp = Transaction(nonce, GASPRICE, 10**5, addr, 0,
                           serpent.encode_datalist([0])).sign(
                               privkey)  #encode datalist...
     print 'sender', new_dcp.sender
     print 'self addr', self_addr
     self.dcp_list[addr] = new_dcp
Exemplo n.º 26
0
def buy():
    ID = request.form.get("id")
    print(ID)
    if current_user.getUsername() == "":
        return login()
    for i in nfts:
        print(ID)
        if ID == i.getID():
            print('ovde si')
            transaction = Transaction(current_user.getAdress(), i.getAdress(),
                                      i.getPrice())
            transaction.send_transaction(request.form.get("private_key"))
            transaction.save_transaction()
            return account()
    return home()
Exemplo n.º 27
0
    def gettx(self, tx_hash):
        """Request a specific transaction.

        :param tx_hash: the hex-encoded transaction hash
        :returns: a :class:`~transactions.Transaction`
        :raises: :exc:`~requests.exceptions.HTTPError`: if the server does not
                 know about the requested transaction (status code 404)
        """
        response = self.request('/transactions/{0}'.format(tx_hash))
        tx_dict = response['transactions'][0]
        tx = Transaction(int(tx_dict['nonce']), int(tx_dict['gasprice']),
                         int(tx_dict['startgas']), tx_dict['to'],
                         int(tx_dict['value']), tx_dict['data'][2:],
                         int(tx_dict['v']), int(tx_dict['r']),
                         int(tx_dict['s']))
        print tx_dict
        return tx
Exemplo n.º 28
0
def new_transaction():
    values = request.get_json()

    # Check that the required fields are in the POST'ed data
    required = ['sender', 'recipient', 'amount']
    if not all(k in values for k in required):
        return 'Missing values', 400

    # Create a new Transaction
    transaction = Transaction(values['sender'], values['recipient'],
                              values['amount'])
    index = transaction.addToLocalDB()

    #index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])

    response = {'message': f'Transaction will be added to Block {index-1}'}
    return jsonify(response), 201
Exemplo n.º 29
0
    def add_transaction(self,
                        recipient,
                        sender,
                        amount=1.0):  #Function to add a transaction
        """ add last blockchain value and a new value to blockchain \n
            Arguments
            sender: sender of amount
            recipient: reciever  of amount
            amount: amount of the transaction
        """

        transaction = Transaction(sender, recipient, amount)

        if VerificationUtils.verify_txn(transaction, self.get_balance):
            self.__open_transactions.append(transaction)
            self.save_data()
            return True
        return False
Exemplo n.º 30
0
    def mine_block(
        self
    ):  #Function to mine blocks (add completed transactions to the blockchain)
        last_block = self.__chain[-1]
        hash_str = hash_block(last_block)
        proof = self.proof_of_work()
        reward_txn = Transaction('Mining', self.hosting_node, MINING_REWARD)

        copied_txn = self.__open_transactions[:]
        copied_txn.append(reward_txn)
        block = Block(previous_hash=hash_str,
                      index=len(self.__chain),
                      transactions=copied_txn,
                      proof=proof)
        self.__chain.append(block)
        self.__open_transactions = []
        self.save_data()
        return True