コード例 #1
0
def verifyBlockCandidate(newBlock, generatorGwPub, generatorDevicePub,
                         alivePeers):
    blockValidation = True
    lastBlk = chainFunctions.getLatestBlock()
    # print("Index:"+str(lastBlk.index)+" prevHash:"+str(lastBlk.previousHash)+ " time:"+str(lastBlk.timestamp)+ " pubKey:")
    lastBlkHash = criptoFunctions.calculateHash(lastBlk.index,
                                                lastBlk.previousHash,
                                                lastBlk.timestamp,
                                                lastBlk.publicKey)
    # print ("This Hash:"+str(lastBlkHash))
    # print ("Last Hash:"+str(block.previousHash))
    if (lastBlkHash != newBlock.previousHash):
        blockValidation = False
        return blockValidation
    if (lastBlk.index != (newBlock.index + 1)):
        blockValidation = False
        return blockValidation
    if (lastBlk.timestamp >= newBlock.timestamp):
        blockValidation = False
        return blockValidation
#TODO -> verifySIGNATURE!!!!!
    if blockValidation:
        voterSign = criptoFunctions.signInfo(gwPvt, newBlock)
        addVoteBlockPBFT(newBlock, gwPub, voterSign)  #adiciona o seu p
        for p in alivePeers:
            p.object.addVoteBlockPBFT(
                newBlock, gwPub,
                voterSign)  #altera a lista de confirmacao de todos os peers
        return True
    else:
        return False
コード例 #2
0
def generateNextBlock(blockData, pubKey, previousBlock, gwPvtKey, consensus):
    """ Receive the information of a new block and create it\n
    @param blockData - information of the new block\n
    @param pubKey - public key of the device how wants to generate the new block\n
    @param previouBlock - BlockHeader object with the last block on the chain\n
    @param gwPvtKey - private key of the gateway\n
    @param consensus - it is specified current consensus adopted
    @return BlockHeader - the new block
    """
    nextIndex = previousBlock.index + 1
    nextTimestamp = time.time()
    previousBlockHash = criptoFunctions.calculateHashForBlock(previousBlock)
    nonce = 0
    nextHash = criptoFunctions.calculateHash(nextIndex, previousBlockHash,
                                             nextTimestamp, pubKey, nonce)
    if (consensus == 'PoW'):
        difficulty_bits = 12  #2 bytes or 4 hex or 16 bits of zeros in the left of hash
        target = 2**(
            256 - difficulty_bits
        )  #resulting value is lower when it has more 0 in the left of hash
        while ((long(nextHash, 16) > target) and (nonce < (2**32))
               ):  #convert hash to long to verify when it achieve difficulty
            nonce = nonce + 1
            nextHash = criptoFunctions.calculateHash(nextIndex,
                                                     previousBlockHash,
                                                     nextTimestamp, pubKey,
                                                     nonce)
    print("####nonce = " + str(nonce))
    sign = criptoFunctions.signInfo(gwPvtKey, nextHash)
    inf = Transaction.Transaction(0, nextHash, nextTimestamp, blockData, sign)

    return BlockHeader.BlockHeader(nextIndex, previousBlockHash, nextTimestamp,
                                   inf, nextHash, nonce, pubKey)
コード例 #3
0
def sendDataTest():
    pub, priv = generateRSAKeyPair()
    temperature = readSensorTemperature()
    t = ((time.time() * 1000) * 1000)
    timeStr = "{:.0f}".format(t)
    data = timeStr + temperature
    signedData = criptoFunctions.signInfo(priv, data)
    ver = criptoFunctions.signVerify(data, signedData, pub)
    print("done: " + str(ver))
コード例 #4
0
def generateNextBlock(blockData, pubKey, previousBlock, gwPvtKey):
    nextIndex = previousBlock.index + 1
    nextTimestamp = time.time()
    nextHash = criptoFunctions.calculateHash(nextIndex, previousBlock.hash,
                                             nextTimestamp, pubKey)
    sign = criptoFunctions.signInfo(gwPvtKey, nextHash)
    inf = Transaction.Transaction(0, nextHash, nextTimestamp, blockData, sign)
    return BlockHeader.BlockHeader(nextIndex, previousBlock.hash,
                                   nextTimestamp, inf, nextHash, pubKey)
コード例 #5
0
ファイル: r2ac.py プロジェクト: eduardo-arruda/r2ac
    def addTransaction(self, devPublicKey, encryptedObj):
        global gwPvt
        global gwPub
        t1 = time.time()
        blk = chainFunctions.findBlock(devPublicKey)

        if (blk != False and blk.index > 0):
            devAESKey = findAESKey(devPublicKey)
            if (devAESKey != False):
                # plainObject contains [Signature + Time + Data]

                plainObject = criptoFunctions.decryptAES(
                    encryptedObj, devAESKey)
                signature = plainObject[:-20]  # remove the last 20 chars
                devTime = plainObject[-20:
                                      -4]  # remove the 16 char of timestamp
                deviceData = plainObject[
                    -4:]  # retrieve the las 4 chars which are the data

                d = devTime + deviceData
                isSigned = criptoFunctions.signVerify(d, signature,
                                                      devPublicKey)

                if isSigned:
                    deviceInfo = DeviceInfo.DeviceInfo(signature, devTime,
                                                       deviceData)
                    nextInt = blk.transactions[len(blk.transactions) -
                                               1].index + 1
                    signData = criptoFunctions.signInfo(gwPvt, str(deviceInfo))
                    gwTime = "{:.0f}".format(((time.time() * 1000) * 1000))
                    # code responsible to create the hash between Info nodes.
                    prevInfoHash = criptoFunctions.calculateTransactionHash(
                        chainFunctions.getLatestBlockTransaction(blk))

                    transaction = Transaction.Transaction(
                        nextInt, prevInfoHash, gwTime, deviceInfo, signData)

                    # send to consensus
                    #if not consensus(newBlockLedger, gwPub, devPublicKey):
                    #    return "Not Approved"

                    chainFunctions.addBlockTransaction(blk, transaction)
                    logger.debug(
                        "block added locally... now sending to peers..")
                    t2 = time.time()
                    logger.debug(
                        "=====2=====>time to add transaction in a block: " +
                        '{0:.12f}'.format((t2 - t1) * 1000))
                    sendTransactionToPeers(
                        devPublicKey, transaction
                    )  # --->> this function should be run in a different thread.
                    #print("all done")
                    return "ok!"
                else:
                    return "Invalid Signature"
            return "key not found"
コード例 #6
0
def sendData():
    temperature = readSensorTemperature()
    t = ((time.time() * 1000) * 1000)
    timeStr = "{:.0f}".format(t)
    data = timeStr + temperature
    # print("data:"+data)
    signedData = criptoFunctions.signInfo(privateKey, data)
    toSend = signedData + timeStr + temperature
    encobj = criptoFunctions.encryptAES(toSend, serverAESKey)
    server.addTransaction(publicKey, encobj)
コード例 #7
0
def sendDataSC(stringSC):
    t = ((time.time() * 1000) * 1000)
    timeStr = "{:.0f}".format(t)
    data = timeStr + stringSC
    signedData = criptoFunctions.signInfo(privateKey, data)
    print("###Printing Signing Data before sending: " + signedData)
    print("###Signature lenght: " + str(len(signedData)))
    toSend = signedData + timeStr + stringSC
    encobj = criptoFunctions.encryptAES(toSend, serverAESKey)
    server.addTransactionSC(publicKey, encobj)
コード例 #8
0
def sendDataTest():
    """ Send fake data to test the system """
    pub, priv = generateRSAKeyPair()
    temperature = readSensorTemperature()
    t = ((time.time() * 1000) * 1000)
    timeStr = "{:.0f}".format(t)
    data = timeStr + temperature
    signedData = criptoFunctions.signInfo(priv, data)
    ver = criptoFunctions.signVerify(data, signedData, pub)
    logger.debug("Sending data teste: " + str(ver))
    print("done: " + str(ver))
コード例 #9
0
ファイル: deviceSimulator.py プロジェクト: brunohlippert/r2ac
def sendData():
    """ Read the sensor data, encrypt it and send it as a transaction to be validated by the peers """
    temperature = readSensorTemperature()
    t = ((time.time() * 1000) * 1000)
    timeStr = "{:.0f}".format(t)
    data = timeStr + temperature
    # print("data:"+data)
    signedData = criptoFunctions.signInfo(privateKey, data)
    toSend = signedData + timeStr + temperature
    encobj = criptoFunctions.encryptAES(toSend, serverAESKey)
    server.addTransaction(publicKey, encobj)
コード例 #10
0
def commitBlockPBFT(newBlock, generatorGwPub, generatorDevicePub, alivePeers):
    threads = []
    if newBlockCandidate[criptoFunctions.calculateHashForBlock(
            newBlock
    )][gwPub] == criptoFunctions.signInfo(
            gwPvt, newBlock
    ):  #if it was already inserted a validation for the candidade block, abort
        print 'block already in consensus'
        return
    if verifyBlockCandidate():  #verify if the block is valid
        for p in alivePeers:
            t = threading.Thread(target=p.object.verifyBlockCandidate,
                                 args=(newBlock, generatorGwPub,
                                       generatorDevicePub, alivePeers))
            threads.append(t)  #call all peers to verify if blocks are valid
            #  join threads
        for t in threads:
            t.join()
コード例 #11
0
ファイル: chainFunctions.py プロジェクト: brunohlippert/r2ac
def generateNextBlock(blockData, pubKey, previousBlock, gwPvtKey, **kwargs):
    """ Receive the information of a new block and create it\n
    @param blockData - information of the new block\n
    @param pubKey - public key of the device how wants to generate the new block\n
    @param previouBlock - BlockHeader object with the last block on the chain\n
    @param gwPvtKey - private key of the gateway\n
    @return BlockHeader - the new block
    """
    nextIndex = previousBlock.index + 1    
    nextTimestamp = time.time()
    #nextHash = criptoFunctions.calculateHash(nextIndex, previousBlock.hash, nextTimestamp, pubKey);
    previousBlockHash = criptoFunctions.calculateHashForBlock(previousBlock)
    nextHash = criptoFunctions.calculateHash(nextIndex, previousBlockHash, nextTimestamp, pubKey)
    sign = criptoFunctions.signInfo(gwPvtKey, nextHash)
    inf = Transaction.Transaction(0, nextHash, nextTimestamp, blockData, sign)

    blockType = kwargs.get('type', None)
    if (blockType):
        return BlockHeader.BlockHeader(nextIndex, previousBlockHash, nextTimestamp, inf, nextHash, pubKey, type=blockType)
    else:
        return BlockHeader.BlockHeader(nextIndex, previousBlockHash, nextTimestamp, inf, nextHash, pubKey)