Exemplo n.º 1
0
    def mineBlock(self, user):
        isChainValid, issueBlock = self.isChainValid()
        if isChainValid:
            miningTransaction = Transaction(fromAddress=convertToPubKey(
                os.getenv("PUB_KEY")),
                                            toAddress=user,
                                            amount=self.minedCoinbase)
            signature = rsa.sign(
                str(miningTransaction).encode(encoding='utf_8'),
                convertToPrivKey(os.getenv("PRIV_KEY")), "SHA-256")
            miningTransaction.addSignature(signature=signature.hex())

            verifiedTransactionsForBlock = []
            for transaction in self.pendingTransactions:
                if self._isTransactionValid(transaction=transaction):
                    verifiedTransactionsForBlock.append(transaction)

            verifiedTransactionsForBlock.insert(0, miningTransaction)

            newBlock = Block(transactions=verifiedTransactionsForBlock,
                             previousHash=self.chain[-1].hashVal,
                             miningDifficulty=self.miningDifficulty)
            self.chain.append(newBlock)
            self.pendingTransactions = self.pendingTransactions - set(
                verifiedTransactionsForBlock)
        else:
            print(
                f"Chain is not valid! Someone tampered with the data! Issue with block {issueBlock}. Removing block {issueBlock} ..."
            )
            if self.debug:
                print("\nBlock which is being removed is:\n")
                print(self.chain[issueBlock])
            self.chain = self.chain[:issueBlock]
Exemplo n.º 2
0
 def mineBlock(pubKeyStr):
     blockchainNetwork.blockchain.mineBlock(user=convertToPubKey(pubKeyStr))
     for node in blockchainNetwork.blockchain.nodes:
         try:
             requests.post(f'http://{node}/mine/broadcast', json={})
         except Exception:
             if blockchainNetwork.debug:
                 print(f"Node {node} not reachable...")
     writeBlockchainToDb(blockchainNetwork=blockchainNetwork)
     return "Block mined!", 201
Exemplo n.º 3
0
    def addTransaction():
        data = request.get_json()
        try:
            valid, messageResponse = isDataValid(data)

            if valid:
                transaction = Transaction(
                    fromAddress=convertToPubKey(data["FromAddress"]),
                    toAddress=convertToPubKey(data["ToAddress"]),
                    amount=int(data["Amount"]))
                signature = rsa.sign(
                    str(transaction).encode(encoding='utf_8'),
                    convertToPrivKey(data["priv_key"]), "SHA-256")
                transaction.addSignature(signature=signature.hex())

                result, message = blockchainNetwork.blockchain.addTransaction(
                    transaction=transaction)

                if result:
                    finalMessage = message + " " + getBalance(
                        data["FromAddress"])[0]
                    writeBlockchainToDb(blockchainNetwork=blockchainNetwork)
                    propagateTransactionToAllNodes(
                        blockchainNetwork=blockchainNetwork,
                        transaction=transaction)
                    return finalMessage, 201

                return message, 400

            else:
                return messageResponse, 500
        except ValueError as e:
            print(e)
            return "Invalid json!", 500
        except OverflowError as e:
            print(e)
            return "Invalid key! Please check both public and private keys", 500
        except KeyError as e:
            print(e)
            return "Missing a field! Please check all required fields are present", 500
        except Exception as e:
            print(e)
            return "Server error!", 500
Exemplo n.º 4
0
    def _isTransactionValid(self, transaction):
        if transaction.signature == "":
            return False, "Signature empty!"

        if not isinstance(transaction, Transaction):
            return False, f"Not a transaction object!\n{transaction}!\n"

        if transaction in self.pendingTransactions:
            return False, f"Transaction already present!\n{transaction}!\n"

        userBalance = self.getBalance(transaction.fromAddress)
        if userBalance < transaction.amount:
            if convertToPubKey(
                    os.getenv("PUB_KEY")) != transaction.fromAddress:
                return False, f"Insufficient balance! You only have {userBalance} coins but you are trying to send {transaction.amount}"

        try:
            rsa.verify(
                str(transaction).encode(encoding='utf_8'),
                bytes.fromhex(transaction.signature), transaction.fromAddress)
        except rsa.VerificationError:
            return False, f"signature not matching!"

        return True, "Valid"
Exemplo n.º 5
0
 def getBalance(pubKeyStr):
     return "Coins left: " + str(
         blockchainNetwork.blockchain.getBalance(
             user=convertToPubKey(pubKeyStr))), 200