Example #1
0
def createNewBlockchain(blockArr):
    blockchain = Blockchain()
    index = 0
    print("BLOCKK DATAA")
    for blockData in blockArr:
        block = Block(blockData['index'], blockData['transactions'],
                      blockData['timestamp'], blockData['prevHash'])
        if (index > 0):
            hashProof = blockData['objHash']
            block.nonce = blockData['nonce']
            # Verify added block along with difficulty of requirements
            addedBlock = blockchain.addBlock(block, hashProof)
            if (not addedBlock):
                # Block not valid and cannot be added
                raise Exception("Chain is tampered.")
        else:
            # Genesis block, no need for verification
            blockchain.chain = []
            # print("this is the genesis block")
            # print(blockData)
            block.objHash = blockData['objHash']
            blockchain.chain.append(block)

        index += 1
    return blockchain
Example #2
0
class Ledger:
    def __init__(self, transactionsPerBlock=1500):
        self.ledgerBlockchain = Blockchain()
        self.transactions = []
        self.TRANSACTIONS_PER_BLOCK = transactionsPerBlock
        self.financeCache = {}

    def validateSignature(self, m, ssig, sk):
        sk = RSA.import_key(sk)
        sValidator = PKCS1_v1_5.new(sk)
        certDigest = SHA256.new()
        certDigest.update(str.encode(m))
        if not sValidator.verify(certDigest, ssig):
            return False
        return True

    def checkUserInLedger(self, uid):
        if not self.financeCache:
            self.buildCache()
        return uid in self.financeCache

    #DOES NOT PERFORM CHECKS RIGHT NOW
    def buildCache(self):
        self.financeCache = {}  #clear data
        for i in range(1, self.ledgerBlockchain.getNumBlocks()):
            block = pickle.loads(self.ledgerBlockchain.getBlockData(i))
            for entry in block:
                rec = entry['receiver']
                amount = entry['amount']

                if rec not in self.financeCache:
                    self.financeCache[rec] = 0

                if entry['type'] in ['reward', 'newUser']:
                    self.financeCache[rec] += amount
                elif entry['type'] == 'transaction':
                    send = entry['sender']
                    if send not in self.financeCache:
                        self.financeCache[send] = 0
                    self.financeCache[send] -= amount
                    self.financeCache[rec] += amount

    def checkBalance(self, uid):
        if uid not in self.financeCache:
            return None
        return self.financeCache[uid]

    def transactionsToBlocks(self):
        while len(self.transactions) >= TRANSACTIONS_PER_BLOCK:
            block = pickle.dumps(self.transactions[0:TRANSACTIONS_PER_BLOCK])
            self.ledgerBlockchain.addBlock(block)
            self.transactions = self.transactions[TRANSACTIONS_PER_BLOCK:]

    def save(self, filename="./ledger.bc"):
        # save as a .bc (blockchain) file
        while len(self.transactions) != 0:
            block = pickle.dumps(self.transactions[0:TRANSACTIONS_PER_BLOCK])
            self.ledgerBlockchain.addBlock(block)
            self.transactions = self.transactions[TRANSACTIONS_PER_BLOCK:]
        self.ledgerBlockchain.save(filename)

    def load(self, filename):
        if type(filename) is not str:
            raise TypeError("Filename must be of type str")
        self.ledgerBlockchain.load(filename)
        self.buildCache()

    #TODO also, need to mix in an index to prevent a repeat attack!

    def addUserToLedger(self, user, amount=0):
        if self.checkUserInLedger(user):
            return (False, "User already exists in ledger")
        data = {'type': 'newUser', 'receiver': user, 'amount': amount}
        self.transactions.append(data)
        self.transactionsToBlocks()
        self.financeCache[user] = amount
        return (True, "User added to ledger")

    def addTransaction(self, data):
        data['type'] = 'transaction'
        senderID = data['sender']
        receiverID = data['receiver']
        amt = data['amount']
        ssig = data['senderSig']
        sPubKey = data['senderPubKey']
        message = str(senderID) + str(receiverID) + str(amt)
        sigsValid = self.validateSignature(message, ssig, sPubKey)
        if not sigsValid:
            return (False, "Invalid Signature(s) detected when adding a " +
                    "transaction. Transaction will not be added")
        hasMoney = self.checkBalance(senderID)
        if not hasMoney or hasMoney < amt:
            return (False,
                    "Sender does not have adequite finances to complete" +
                    "this transaction. Transaction will not be added")

        self.transactions.append(data)
        self.transactionsToBlocks()
        self.financeCache[receiverID] += amt
        self.financeCache[senderID] -= amt

        return (True, "Transaction added")

    def addBlockReward(self, reciever, amount):
        # validation
        if not self.checkUserInLedger(reciever):
            raise Exception(
                "Tried to add a block reward to a user that doesn't exist.")
        if type(amount) is not int:
            raise TypeError("amount must be of type int")
        data = {'type': 'reward', 'receiver': reciever, 'amount': amount}

        self.transactions.append(data)
        self.transactionsToBlocks()
        self.financeCache[reciever] += amount

        return (True, "Reward added")
Example #3
0
import os, time

from block import Block
from blockchain import Blockchain

if not os.path.exists("blocks"):
    os.makedirs("blocks")
testBlockchain = Blockchain(4, 42)

for i in range(100):

    block = Block(len(testBlockchain.chain), time.ctime())
    print("".join([
        "[Info] Mining block ",
        str(block.index), " with difficulty ",
        str(testBlockchain.difficulty), "... "
    ]))
    testBlockchain.addBlock(block)

    if testBlockchain.isValid():
        print("\n[Info] Is blockchain valid? ", str(testBlockchain.isValid()))
    else:
        print("\n[Error] Is blockchain valid? ", str(testBlockchain.isValid()))
class P2PServerFactory(Factory):

    protocol = P2PServerProtocol

    def __init__(self):
        self.state = 'READY'
        self.blockchain = Blockchain()
        self.lastPeer = None
        self.peers = {}
        self.peerCons = {}
        self.contractsWaiting = []
        self.replies = {'yes': 0, 'no': 0}
        self.votesReceived = set()
        self.lastVoteReceived = None
        self.target = 0
        self.newBlock = None
        self.validateLoop = task.LoopingCall(self.blockchain.validateChain)
        self.validateLoop.start(300)

    def consensus(self):
        if self.replies['yes'] > self.target / 2:
            self.blockchain.addBlock(self.newBlock)
            print('Block Added:')
            self.newBlock.printBlock()
            message = json.dumps({
                'type':
                'current block',
                'index':
                str(self.newBlock.getIndex()),
                'previous hash':
                self.newBlock.getPreviousHash(),
                'timestamp':
                self.newBlock.getTimestamp(),
                'contract':
                self.newBlock.getContract(),
                'hash':
                self.newBlock.getHash()
            })
            for peer in self.peers:
                self.peerCons[peer].transport.write(
                    str.encode(message + '\r\n'))
        if self.contractsWaiting:
            currentBlock = self.blockchain.getCurrentBlock()
            self.newBlock = Block(currentBlock.getIndex() + 1,
                                  currentBlock.getHash(),
                                  self.contractsWaiting.pop(0))
            self.resetConsensus()
            self.sendNewBlock()
        elif self.replies['yes'] + self.replies['no'] != self.target:
            self.resendNewBlock()
        else:
            print('state: READY')
            self.state = 'READY'

    def sendNewBlock(self):
        message = json.dumps({
            'type': 'new block',
            'index': str(self.newBlock.getIndex()),
            'previous hash': self.newBlock.getPreviousHash(),
            'timestamp': self.newBlock.getTimestamp(),
            'contract': self.newBlock.getContract(),
            'hash': self.newBlock.getHash()
        })
        self.peerCons[self.lastPeer].transport.write(
            str.encode(message + '\r\n'))
        self.resend = reactor.callLater(60, self.resendNewBlock)

    def resendNewBlock(self):
        self.resetConsensus()
        self.sendNewBlock()
        print('Block Resent')

    def resetConsensus(self):
        self.replies['yes'] = 0
        self.replies['no'] = 0
        self.votesReceived = set()
        self.lastVoteReceived = None
        self.target = len(self.peers)
Example #5
0
class Node:
    def __init__(self, myIp, myPort):
        # self.lock = threading.Lock()
        self.money = {}
        self.firstTime = 0
        self.lastTime = 0
        self.blockTimes = []
        self.legitTransactions = []
        self.tempUsedOutputs = {}
        self.isMining = False
        self.winningBlockFound = False
        self.existsConflict = False
        self.isStillAdjusting = False
        self.transactionPool = deque([])
        self.myIp = myIp
        self.myPort = myPort
        self.chain = Blockchain()
        self.wallet = self.createWallet()
        self.nodeId = -1
        self.workingBlock = None
        self.ring = []
        self.unspentTransactionsMap = {}

    def jsonToTransaction(self, jsonTransaction):
        jsonTransaction = json.loads(jsonTransaction)
        outputs = []
        transactionOutputs = jsonTransaction['transactionOutputs']
        for transactionOutput in transactionOutputs:
            output = TransactionOutput(
                address=transactionOutput['address'],
                amount=transactionOutput['amount'],
                transactionId=transactionOutput['transactionId'],
                id=transactionOutput['id'])
            outputs.append(output)
        transaction = Transaction(
            senderAddress=jsonTransaction['senderAddress'],
            receiverAddress=jsonTransaction['receiverAddress'],
            amount=jsonTransaction['amount'],
            transactionId=jsonTransaction['transactionId'],
            signature=jsonTransaction['signature'],
            transactionInputs=jsonTransaction['transactionInputs'],
            transactionOutputs=outputs)
        return transaction

    def jsonToBlock(self, jsonBlock):
        jsonBlock = json.loads(jsonBlock)
        listOfTransactions = jsonBlock['listOfTransactions']
        transactions = []
        for jsonTransaction in listOfTransactions:
            transactions.append(
                self.jsonToTransaction(json.dumps(jsonTransaction, indent=4)))
        block = Block(previousHash=jsonBlock['previousHash'],
                      index=jsonBlock['index'],
                      timestamp=jsonBlock['timestamp'],
                      currentHash=jsonBlock['currentHash'],
                      nonce=jsonBlock['nonce'],
                      listOfTransactions=transactions)
        return block

    def jsonToBlockchain(self, jsonChain):
        blockchain = Blockchain()
        for jsonBlock in jsonChain:
            blockchain.blocks.append(
                self.jsonToBlock(json.dumps(jsonBlock, indent=4)))
        return blockchain

    def unicast(self, address, body):
        headers = {'Content-type': 'application/json'}
        return requests.post(url=address, data=body, headers=headers).json()

    def broadcast(self, addressSuffix, body):
        for node in self.ring:
            address = 'http://' + node['ip'] + ':{0}'.format(
                node['port']) + addressSuffix
            threading.Thread(target=self.unicast, args=[address, body]).start()

    def isBootstrapNode(self):
        return self.nodeId == 0

    def createUnspentTransactionsMap(self):
        for node in self.ring:
            self.unspentTransactionsMap[node['address']] = {}
        self.unspentTransactionsMap[self.wallet.address] = dict()
        genesisTransactionOutput = self.chain.blocks[0].listOfTransactions[
            0].transactionOutputs[0]
        self.insertIntoUnspentTransactionMap(genesisTransactionOutput.address,
                                             genesisTransactionOutput)

    def insertIntoUnspentTransactionMap(self, address, transactionOutput):
        self.unspentTransactionsMap[address][
            transactionOutput.id] = transactionOutput

    def createWallet(self):
        return Wallet()

    def createNewBlock(self, previousHash, index):
        return Block(previousHash, index)

    def registerNodeToRing(self, ip, port):
        address = 'http://' + ip + ':{0}'.format(port) + '/bootstrap/register'
        body = json.dumps(
            {
                'ip': self.myIp,
                'port': self.myPort,
                'address': self.wallet.address
            },
            indent=4)
        reply = self.unicast(address, body)
        self.nodeId = reply['nodeId']
        address = 'http://' + ip + ':{0}'.format(
            port) + '/bootstrap/registerAck'
        body = json.dumps({'nodeId': self.nodeId}, indent=4)
        reply = self.unicast(address, body)
        print(reply['msg'])

    def walletBalance(self, address):
        total = 0
        unspent = self.unspentTransactionsMap[address]
        for transactionOutput in unspent.values():
            total += transactionOutput.amount
        return total

    def myWalletBalance(self):
        return self.walletBalance(self.wallet.address)

    def createTransaction(self, senderAddress, amount, receiverAddress):
        if amount <= 0:
            return 'You can not give nor negative nor zero money', False
        # unspent = self.unspentTransactionsMap[senderAddress]
        # hasMoney = 0
        # transactionInputs = []
        # for id, transactionOutput in unspent.items():
        #     hasMoney += transactionOutput.amount
        #     transactionInputs.append(id)
        #     if hasMoney >= amount:
        #         break

        unspent = self.money
        hasMoney = 0
        transactionInputs = []
        for id, transactionOutput in unspent.items():
            hasMoney += transactionOutput.amount
            transactionInputs.append(id)
            if hasMoney >= amount:
                break

        if hasMoney < amount:
            return 'Not enough money', False
        transaction = Transaction(senderAddress=senderAddress,
                                  receiverAddress=receiverAddress,
                                  amount=amount,
                                  transactionInputs=transactionInputs,
                                  senderPrivateKey=self.wallet.privateKey)

        senderMoney = hasMoney - transaction.amount
        if not (senderMoney == 0):
            senderTransactionOutput = TransactionOutput(
                address=transaction.senderAddress,
                amount=senderMoney,
                transactionId=transaction.transactionId)
            transaction.transactionOutputs.append(senderTransactionOutput)
            self.money[senderTransactionOutput.id] = senderTransactionOutput
        for inputId in transactionInputs:
            try:
                self.money.pop(inputId)
            except:
                pass

        return transaction, True

    def verifySignature(self, transaction):
        publicKey = RSA.importKey(binascii.unhexlify(
            transaction.senderAddress))
        verifier = PKCS1_v1_5.new(publicKey)
        digest = SHA256.new(
            json.dumps(
                transaction.toDict([
                    'senderAddress', 'receiverAddress', 'amount',
                    'transactionInputs'
                ])).encode())
        return verifier.verify(digest,
                               binascii.unhexlify(transaction.signature))

    def validateTransaction(self, transaction):
        def doIt(id):
            elem = self.unspentTransactionsMap[transaction.senderAddress].pop(
                id)
            self.tempUsedOutputs[id] = [elem, transaction.senderAddress]
            return elem

        flag1 = self.verifySignature(transaction)
        availableIds = list(
            self.unspentTransactionsMap[transaction.senderAddress].keys())
        flag2 = all(id in availableIds for id in transaction.transactionInputs)
        if not (flag1 and flag2):
            return None, False
        unspentToUse = [doIt(id) for id in transaction.transactionInputs]
        moneyToUse = 0
        for transactionOutput in unspentToUse:
            moneyToUse += transactionOutput.amount
        senderMoney = moneyToUse - transaction.amount
        if not (senderMoney == 0):
            senderTransactionOutput = TransactionOutput(
                address=transaction.senderAddress,
                amount=senderMoney,
                transactionId=transaction.transactionId)
            transaction.transactionOutputs.append(senderTransactionOutput)
            self.unspentTransactionsMap[senderTransactionOutput.address][
                senderTransactionOutput.id] = senderTransactionOutput
        receiverTransactionOutput = TransactionOutput(
            address=transaction.receiverAddress,
            amount=transaction.amount,
            transactionId=transaction.transactionId)
        transaction.transactionOutputs.append(receiverTransactionOutput)
        self.unspentTransactionsMap[receiverTransactionOutput.address][
            receiverTransactionOutput.id] = receiverTransactionOutput

        if receiverTransactionOutput == self.wallet.address:
            self.money[
                receiverTransactionOutput.id] = receiverTransactionOutput

        return transaction, True

    def broadcastTransaction(self, transaction):
        addressSuffix = '/transactions/broadcast'
        body = json.dumps(transaction.toDictAll(), indent=4)
        self.broadcast(addressSuffix, body)

    def transact(self, senderAddress, amount, reiceverAddress):
        transaction, flag = self.createTransaction(senderAddress, amount,
                                                   reiceverAddress)
        if not flag:
            return transaction, False
        # flag1 = self.verifySignature(transaction)
        # unspent = self.unspentTransactionsMap[transaction.senderAddress]
        # availableIds = list(unspent.keys())
        # flag2 = all(id in availableIds for id in transaction.transactionInputs)
        # if not (flag1 and flag2):
        #     return 'Transaction is invalid', False
        self.broadcastTransaction(transaction)
        self.transactionPool.append({transaction.transactionId: transaction})
        return 'Transaction created successfully', True

    def receiveTransaction(self, jsonTransaction):
        transaction = self.jsonToTransaction(
            json.dumps(jsonTransaction, indent=4))
        self.transactionPool.append({transaction.transactionId: transaction})

    def pullTransactionFromPool(self):
        if self.isMining or self.winningBlockFound or self.existsConflict or self.isStillAdjusting:
            # print(self.isMining)
            # print(self.winningBlockFound)
            # print(self.existsConflict)
            # print(self.isStillAdjusting)
            return
        if len(self.transactionPool) != 0:
            transactionDict = self.transactionPool.popleft()
            # print(transactionDict)
            pooledTransaction = list(transactionDict.values())[0]
            if pooledTransaction.transactionId in self.legitTransactions:
                return
            transaction, flag = self.validateTransaction(pooledTransaction)
            if transaction is None:
                # time.sleep(2)
                # pooledTransaction.remainingTries -= 1
                # self.transactionPool.appendleft({pooledTransaction.transactionId: pooledTransaction})
                return
            if transaction.remainingTries > 0 and flag:
                self.workingBlock.addTransaction(transaction)
                if len(self.workingBlock.listOfTransactions) >= CAPACITY:
                    self.isMining = True
                    print('==> Start Mining')
                    self.mineBlock()

    def validateBlock(self, block):
        self.lastTime = time.time()
        tempBlock = Block(previousHash=block.previousHash,
                          index=block.index,
                          timestamp=block.timestamp,
                          nonce=block.nonce,
                          listOfTransactions=block.listOfTransactions)
        if tempBlock.hash(
        ) == block.currentHash and block.previousHash == self.chain.lastBlockHash(
        ):
            return True
        else:
            return False

    def mineBlock(self):
        tic = time.perf_counter()
        while (not self.workingBlock.pow()) and not self.winningBlockFound:
            self.workingBlock.nonce += 1
        toc = time.perf_counter()
        diff = toc - tic
        self.blockTimes.append(diff)
        if not self.winningBlockFound:  # check
            print('==> Found PoW. Broadcasting...')
            if self.validateBlock(self.workingBlock):
                self.isMining = False
                self.chain.addBlock(self.workingBlock)
                self.broadcastBlock()
            else:
                print('Wtf this cannot be happening --mineBlock')
        else:
            print('==> Someone else solved the puzzle')
        self.winningBlockFound = False

    def broadcastBlock(self):
        addressSuffix = '/block/broadcast'
        body = json.dumps(self.workingBlock.toDictAll(), indent=4)
        self.broadcast(addressSuffix, body)
        winningTransactionsIds = [
            transaction.transactionId
            for transaction in self.workingBlock.listOfTransactions
        ]
        self.legitTransactions += winningTransactionsIds
        self.workingBlock = Block(previousHash=self.chain.lastBlockHash(),
                                  index=self.chain.lastBlockIndex() + 1)

    def receiveBlock(self, jsonBlock):
        self.winningBlockFound = True
        self.isMining = False
        block = self.jsonToBlock(jsonBlock)
        if self.validateBlock(block):
            self.chain.addBlock(block)
        else:
            print('==> Conflict detected. Asking the others...')
            self.existsConflict = True
            self.resolveConflict()
            self.existsConflict = False
        self.isStillAdjusting = True
        self.adjust(self.chain.blocks[-1])

        self.money = dict(self.unspentTransactionsMap[self.wallet.address])

        self.tempUsedOutputs = {}
        self.workingBlock = Block(previousHash=self.chain.lastBlockHash(),
                                  index=self.chain.lastBlockIndex() + 1)
        self.isStillAdjusting = False
        time.sleep(0.8)
        self.winningBlockFound = False

    # thelei akomh kai to unspentTransactionsMap klp

    def resolveConflict(self):
        addressSuffix = '/chain/conflict/length'
        ipAddress = ''
        port = -1
        headers = {'Content-type': 'application/json'}
        length = len(self.chain)
        for node in self.ring:
            address = 'http://' + node['ip'] + ':{0}'.format(
                node['port']) + addressSuffix
            tempLength = requests.get(url=address,
                                      headers=headers).json()['length']
            if tempLength > length:
                length = tempLength
                ipAddress = node['ip']
                port = node['port']
        if length == len(self.chain):
            return
        address = 'http://' + ipAddress + ':{0}'.format(
            port) + '/chain/conflict/blockchain'
        jsonChain = requests.get(url=address, headers=headers).json()
        jsonChain = json.loads(jsonChain['chain'])['chain']
        chain = self.jsonToBlockchain(jsonChain)
        if self.validateChain(chain):
            print('Conflict Resolved')
            self.legitTransactions = []
            self.chain = chain
            for node in self.ring:
                self.unspentTransactionsMap[node['address']] = {}
            self.unspentTransactionsMap[self.wallet.address] = dict()
            transactionInputsIds = []
            transactionOutputs = []
            for block in self.chain.blocks:
                for transaction in block.listOfTransactions:
                    self.legitTransactions.append(transaction.transactionId)
                    for transactionInput in transaction.transactionInputs:
                        transactionInputsIds.append(transactionInput)
                    for transactionOutput in transaction.transactionOutputs:
                        transactionOutputs.append(transactionOutput)
            toKeepTransactionOutputs = [
                transactionOutput for transactionOutput in transactionOutputs
                if transactionOutput.id not in transactionInputsIds
            ]
            for transactionOutput in toKeepTransactionOutputs:
                self.unspentTransactionsMap[transactionOutput.address][
                    transactionOutput.id] = transactionOutput
        else:
            print('Wtf this cannot be happening --resolveConflict')

    def validateChain(self, chain):
        genesisBlock = self.chain.blocks[0]
        self.chain.blocks = [genesisBlock]
        for i in range(1, len(chain)):
            if not self.validateBlock(chain.blocks[i]):
                # print('False')
                return False
            self.chain.addBlock(chain.blocks[i])
        # print('True')
        return True

    def adjust(self, winningBlock):
        mineTransactionsIds = [
            transaction.transactionId
            for transaction in self.workingBlock.listOfTransactions
        ]
        winningTransactionsIds = [
            transaction.transactionId
            for transaction in winningBlock.listOfTransactions
        ]

        self.legitTransactions += winningTransactionsIds
        # t1 --> transactions dika mou oxi sto winning block pou elava omws
        # t2 --> transactions sto winning block alla oxi se emena

        t1 = [
            transaction for transaction in self.workingBlock.listOfTransactions
            if transaction.transactionId not in winningTransactionsIds
        ]
        t2 = [
            transaction for transaction in winningBlock.listOfTransactions
            if transaction.transactionId not in mineTransactionsIds
        ]

        # print(mineTransactionsIds)
        # print(winningTransactionsIds)
        # print(t1)
        # print(t2)

        # t2Inputs --> ta transactionInputs pou xrhsimopoihthikan sto winning block
        # t2InputsAddresses --> h antistoixh sender address gia kathe apo ta parapanw transaction inputs

        t2Inputs = []
        t2InputsAddresses = []
        for transaction in t2:
            for transactionInput in transaction.transactionInputs:
                t2Inputs.append(transactionInput)
                t2InputsAddresses.append(transaction.senderAddress)

        # cleanTransactions --> ta transactions tou t1 pou mporoun na xrhsimopoihthoun autousia pali
        # dirtyTransactions --> ta transactions tou t1 pou eixan toulaxiston ena transaction input koino me ta transaction inputs
        #                       tou winning block, kai etsi tha prepei ek neou na desmeutoun poroi kai na ginei validate
        # toBeUsedAgainTransactionInputs --> ta transaction inputs tou sunolou t1 pou mporoun na ksanaxrhsimopoithoun

        cleanTransactions = []
        dirtyTransactions = []
        toBeUsedAgainTransactionInputs = []

        # print(t2Inputs)
        # print(t2InputsAddresses)

        # prosdiorismos twn domwn cleanTransactions, dirtyTransactions, toBeUsedAgainTransactionInputs

        for transaction in t1:
            sendBack = False
            for i in range(0, len(transaction.transactionInputs)):
                if transaction.transactionInputs[i] in t2Inputs:
                    # t2Inputs.pop(i)
                    # t2InputsAddresses.pop(i)
                    sendBack = True
                else:
                    toBeUsedAgainTransactionInputs.append(
                        transaction.transactionInputs[i])
            if sendBack == True:
                dirtyTransactions.append(transaction)
            else:
                cleanTransactions.append(transaction)

        # print(toBeUsedAgainTransactionInputs)

        # proshtetoume sto unspentTransactionsMap ta transactionInputs pou mporoun na xrhsimopoihthoun kai pali

        # print(cleanTransactions)
        # print(dirtyTransactions)

        # print(self.unspentTransactionsMap)

        for transactionInput in toBeUsedAgainTransactionInputs:
            try:
                temp = self.tempUsedOutputs[transactionInput]
                self.unspentTransactionsMap[temp[1]][temp[0].id] = temp[0]
            except:
                pass

        # gia kathe transaction tou sunolou t2 prosthetoume ta transaction outputs ston unspentTransactionsMap mas

        for transaction in t2:
            for transactionOutput in transaction.transactionOutputs:
                self.unspentTransactionsMap[transactionOutput.address][
                    transactionOutput.id] = transactionOutput

        # afairoume apo to unspentTransactionsMap ta transactionInputs pou anhkan sto winning block

        for i in range(0, len(t2Inputs)):
            try:
                self.unspentTransactionsMap[t2InputsAddresses[i]].pop(
                    t2Inputs[i])
            except:
                pass

        for transaction in t1:
            for transactionOutput in transaction.transactionOutputs:
                try:
                    self.unspentTransactionsMap[transactionOutput.address].pop(
                        transactionOutput.id)
                except:
                    pass

        # gia kathe dirty transaction pou eixame ftiaksei afairoume ta transactionOutputs pou auto eixe paragei
        # kai sthn sunexeia dokimazoume ek neou na to ftiaksoume. An ginetai to prosthetoume sta cleanTransactions,
        # alliws to petame

        # for transaction in dirtyTransactions:
        #     tempTransaction, flag = self.createTransaction(
        #         senderAddress=transaction.senderAddress, amount=transaction.amount,
        #         receiverAddress=transaction.receiverAddress)
        #     if not flag:
        #         print('Found invalid transaction')
        #     else:
        #         tempTransaction.remainingTries = transaction.remainingTries
        #         cleanTransactions.append(tempTransaction)

        # print(self.unspentTransactionsMap)

        # epanatopothetoume sto transaction pool kathe clean transaction afou meiwsoume ton deikth remaining tries

        for transaction in cleanTransactions:
            transaction.remainingTries -= 1
            transaction.transactionOutputs = []
            self.transactionPool.appendleft(
                {transaction.transactionId: transaction})

        # for node in self.ring:
        #     print(node['nodeId'])
        #     print(self.walletBalance(node['address']))
        # print(self.nodeId)
        # print(self.myWalletBalance())
        return

    def printTransactionPool(self):
        print(len(self.transactionPool))
        print(
            '==============================================================================='
        )
        for transaction in self.transactionPool:
            for value in list(transaction.values()):
                print(value)
        print(
            '==============================================================================='
        )

    def printUnspentTransactionsMap(self):
        print(len(self.unspentTransactionsMap))
        for address, unspent in list(self.unspentTransactionsMap.items()):
            print(
                '==============================================================================='
            )
            print(address)
            for id, output in unspent.items():
                print(
                    '---------------------- {0} ----------------------'.format(
                        id))
                print(output)
                print(
                    '-----------------------{0}-----------------------'.format(
                        '-' * len(id)))
            print(
                '==============================================================================='
            )

    def printTempUsedOutputs(self):
        for id, output in self.tempUsedOutputs.items():
            print(
                '---------------------- {0} ----------------------'.format(id))
            print(output)
            print('-----------------------{0}-----------------------'.format(
                '-' * len(id)))
        print(
            '==============================================================================='
        )
Example #6
0
def add_block(transaction):
	blockchain = Blockchain()
	blockchain.addBlock(transaction)
Example #7
0
        else:
            booCheck=False
            break
    if(booCheck):
        print("\nTudo ok\n")
    else:
        print("Falha blockchain comprometida\n")

        

for i in range(0,100):
    data = {1:"maria",2:"jose",3:"joao"}
    block = Block()
    block.setData(data[randint(1, 3)],randint(1, 9))
    block.setData(data[randint(1, 3)],randint(1, 9))
    block.setData(data[randint(1, 3)],randint(1, 9))
    blockchain.addBlock(block)


while 1:
    print("A blockchain foi gerada, escolha se quer validar:")
    print("1 para validar")
    print("2 para sair")
    a = int(input("Escolha: " ))
    
    if(a==1):
        validate()
    elif(a==2):
        break
    else:
        print("\nEscolha incorreta\n")
Example #8
0
class Client:
    """
	Test Client
	Something like Controller.
	Here I create blockchain and wallets
	"""
    def __init__(self):
        """
		
		"""
        self.wallets = {}
        # Initialise wallets of participaters
        # And give 100 Nicecoins to each of them
        self.walletA = self.registerWallet(Wallet(100))
        self.walletB = self.registerWallet(Wallet(100))

        # Init Nicecoin BlockChain
        genesisBlock = Block([], 0)
        self.blockchain = Blockchain(genesisBlock)

        # It is handler that will execute when transaction will be succeeded
        def onBlockReadyHandler(transactions):
            print("[Transacton completed]")
            for transaction in transactions:
                wallet = self.wallets[transaction.recipient_address]

                if (wallet is not None):
                    print("W: %s gain: %d" %
                          (transaction.recipient_address, transaction.amount))
                    wallet.amount = wallet.amount + transaction.amount
            self.debug()

        self.blockchain.addOnBlockReadyHandler(onBlockReadyHandler)

    def initTransactions(self):
        # Create transfers between wallets
        # Add transactions in blockchain
        self.debug()
        self.trans1 = self.walletA.transfer(self.walletB.address, 10)
        self.trans2 = self.walletB.transfer(self.walletA.address, 20)
        trans3 = self.walletB.transfer(self.walletA.address, 5)

        # The transacton instance may be equal to None if there wer not enough money in wallet
        if self.trans1 != None and self.blockchain.addTransaction(self.trans1):
            print "Trans1 was successfully added"
        if self.trans2 != None and self.blockchain.addTransaction(self.trans2):
            print "Trans2 was successfully added"
        if trans3 != None and self.blockchain.addTransaction(trans3):
            print "Trans3 was successfully added"

        self.examineDuplicationTransactions()
        # Display changes in wallets
        self.debug()
        # Try to add trans1

    def examineDuplicationTransactions(self):
        # Examine duplications
        if self.trans2 != None and self.blockchain.addTransaction(self.trans2):
            # Fail
            print "Copy of Trans2 was successfully added!!!"
        else:
            print "Copy of Trans2 was rejected"

    def addBlock(self):
        block, computeTime = self.blockchain.addBlock()
        print("[Add Block] # %d %s %f" %
              (block.index, block.hash, computeTime))
        self.debug()

    def debug(self):
        print("[D] A: %d NC, B: %d NC, #trans: %d" %
              (self.walletA.amount, self.walletB.amount,
               len(self.blockchain.transactions)))

    def dump(self):
        print("[Blockchain]")
        for block in self.blockchain.chain:
            print("# %d %s" % (block.index, block.hash))

    def registerWallet(self, wallet):
        self.wallets[wallet.address] = wallet
        return wallet
Example #9
0
from blockchain import Blockchain
from block import Block

blockchain = Blockchain()

block1 = Block(blockchain.getLastId(), blockchain.getLastHash(), "Test 2")
blockchain.addBlock(block1)

block2 = Block(blockchain.getLastId(), blockchain.getLastHash(), "Test 3")
blockchain.addBlock(block2)