コード例 #1
0
ファイル: miner.py プロジェクト: cpcdoy/koku
def main():

    try:
        if os.path.exists('/tmp/.koku.chain'):
            with open('/tmp/.koku.chain', 'rb') as cfile:
                chain = pickle.load(cfile)
                logger.info("Chain found until block #" + str(chain[-1].id))
        else:
            chain = [ Block(b'', b'', 0) ]
    except Exception as inst:
        logger.exception("Koku blockchain file not found")
        logger.error(type(inst))
        logger.error((inst.args))

    miner = gpu_miner(logger)
    net = KokuNetwork(KokuNetworkPeerType.MINER, logger, chain, miner)
    #time.sleep(3)
    net.broadcastMessage(KokuMessageType.GET_ADDR, [])
    #time.sleep(3)
    net.broadcastMessage(KokuMessageType.GET_FROM_LAST, chain[-1].id)
    #J'ai ajouté logging ici pour que le network puisse en faire. C'est dans /tmp/koku.log
    #Ici il faut récupérer pleins de peers, je pense que c'est bon.
    #while not updateChain(net):
    #    logging.error('An error in the downloaded chain has been detected!')

    vk = sk.get_verifying_key()

    #chain[0].setTransactions([Transaction(42, 42, getAddr(vk), vk)])
    for b in chain:
        net.transactions[b.id] = b.transactions

    while True:
        try:
            transactions = getInitTransactions(vk, sk)
            newBlock = Block(chain[-1].getHash(), b'', len(chain))
            newBlock.setTransactions(transactions)

            miner.set_block(newBlock)
            nounce, fresh = miner.compute_hashes()
            if fresh:
                chain.append(nounce)
                net.transactions[nounce.id] = nounce.transactions
                net.broadcastMessage(KokuMessageType.FROM_LAST, [nounce])
                with open('/tmp/.koku.chain', 'wb') as f:
                    dump = pickle.dumps(chain)
                    f.write(dump)

        except Exception as inst:
            logger.exception("Main loop exception")
            logger.error(type(inst))
            logger.error((inst.args))
コード例 #2
0
    def compute_hashes(self):
        try:
            self.logger.info(self.data_info)
            self.logger.info(self.blocks)
            output = np.zeros(8 * self.globalThreads, np.uint32)
            mf = cl.mem_flags

            self.not_interrupted = True
            passes = 0
            global_index = 0
            data_len = self.data_info[0]
            b = self.def_block
            self.logger.info(self.data_info)
            while self.not_interrupted:
                self.logger.info('Pass ' + str(passes))
                passes += 1
                for i in range(self.globalThreads):
                    b.pad = self.nounce_begin + global_index

                    self.blocks[i * data_len: (i + 1) * data_len] = np.frombuffer(b.getPack()[:], np.uint8)
                    global_index += 1

                self.logger.info('Transfering data...')
                data_info_buf = cl.Buffer(self.context, mf.READ_ONLY  | mf.USE_HOST_PTR, hostbuf=self.data_info)
                plain_key_buf = cl.Buffer(self.context, mf.READ_ONLY  | mf.USE_HOST_PTR, hostbuf=self.blocks)
                output_buf = cl.Buffer(self.context, mf.WRITE_ONLY | mf.USE_HOST_PTR, hostbuf=output)

                self.logger.info('Starting computation...')
                exec_evt = self.miner.sha256_crypt_kernel(self.queue, (self.globalThreads, ), (self.localThreads, ), data_info_buf,  plain_key_buf, output_buf)
                exec_evt.wait()
                cl.enqueue_read_buffer(self.queue, output_buf, output).wait()

                for j in range(self.globalThreads):
                    if output[j * 8] < self.difficulty:
                        for i in range(8):
                            self.logger.info(format(output[j * 8 + i], '02x'))
                        self.logger.info('')
                        self.logger.info('Truth: ' + str(hashlib.sha256(self.blocks[j * self.data_info[0]:(j+1) * self.data_info[0]]).hexdigest()))
                        self.logger.info("Block found")
                        a = Block(b'', b'', 0)
                        a.unpack(self.blocks[j * self.data_info[0]:(j+1) * self.data_info[0]])
                        return (a, True) if self.not_interrupted else (a, False)

                    #self.logger.info('')
                self.logger.info('Time to compute: ' + str(1e-9 * (exec_evt.profile.end - exec_evt.profile.start)))
            return (self.def_block, False)
        except Exception as inst:
            self.logger.exception("Compute hashes")
            self.logger.error(type(inst))
            self.logger.error((inst.args))
コード例 #3
0
ファイル: wumbo.py プロジェクト: JasonDavidoff85/wumboCoin
class wumbo():
    def __init__(self, privKey=None):
        self.crypto = Crypto(privKey)
        # set current block
        self.block = Block(self, 'blockchain/current.wub')

    def importKey(self, path):
        self.crypto.importKey(path)

    def makeKeys(self):
        return self.crypto.createKey()

    def giveCoins(self, sender, receiver, amount):
        transaction = {
            'sender': sender,
            'receiver': receiver,
            'amount': amount
        }
        return self.block.addTransaction(transaction)

    def getBlock(self, blockNum):
        blocks = os.listdir('blockchain/')

        files = {i.split(".")[0]: i for i in blocks}
        files.setdefault(blockNum, None)
        if files[blockNum] == None:
            return {"block not found": True}

        with open('blockchain/{}'.format(files[blockNum]), 'r') as f:
            blockData = json.load(f)

        return blockData

    def getPubKey(self):
        return self.crypto.getPubKey().decode("utf-8")

    # todo: def makeBulkTransactions():

    # opens up /blockchain
    # checks integrity of chain
    # sets self.block
    def syncChain(self):
        try:
            blocks = os.listdir('blockchain/')
        except OSError as err:
            print("key import error\n{0}".format(err))
コード例 #4
0
ファイル: level.py プロジェクト: Lagostra/snakes
    def init_from_json(self, json):
        self.snakes = []
        self.apples = []
        self.blocks = []

        self.dimensions = (json['level_size']['width'], json['level_size']['height'])

        for snake in json['snakes']:
            self.snakes.append(Snake((snake['x'], snake['y']), snake['id'], snake['dir']))

        self.snakes.sort(key=lambda x: x.id)

        for apple in json['apples']:
            self.apples.append(Apple((apple['x'], apple['y'])))

        for block in json['blocks']:
            self.apples.append(Block((block['x'], block['y'])))
コード例 #5
0
ファイル: miner.py プロジェクト: trog-levrai/koku
from common.block import getDifficulty
from daemonize import Daemonize
from optparse import OptionParser
from common.p2p2 import KokuStruct
from common.block import checkChain
from common.p2p2 import KokuNetwork
from common.p2p2 import KokuMessageType
from common.p2p2 import KokuNetworkPeerType
from common.transaction import Transaction
#from gpu.gpu_miner import gpu_miner
from common.cpu_miner import cpu_miner

pid = "/tmp/koku.pid"
sk = None
addr = ''
chain = [ Block(b'', b'', 0) ]
net = None
logger = None
miner = None

def print_chain(logger, chain):
    for i, b in enumerate(chain):
        logger.info(str(i) + ' : ' + str(b.time) + ' : '  + b58encode(b.getHash()))

def getInitTransactions(vk, sk):
    tr = Transaction(10, 0, getAddr(vk), vk)
    #We do that because this transaction is the reward
    tr.sender = b''
    #We don't sign it bc no signature is needed
    return [tr]
コード例 #6
0
ファイル: game_logic.py プロジェクト: Lagostra/snakes
    def check_collision(self, level):
        snakes_collided = []
        # check box collision
        for snake in level.snakes:
            if snake.body[0] in map(lambda x: x.position, level.blocks):
                level.blocks.extend(list(map(lambda x: Block(x), (filter(lambda x: x != snake.body[0], snake.body)))))
                snakes_collided.append(snake)
        # check wall collision
        for snake in level.snakes:
            if snake.body[0][0] <= -level.dimensions[0]/2 - 1 or snake.body[0][0] >= level.dimensions[0]/2:
                level.blocks.extend(list(map(lambda x: Block(x), (filter(lambda x: x != snake.body[0], snake.body)))))
                snakes_collided.append(snake)
            if snake.body[0][1] <= -level.dimensions[1]/2 - 1 or snake.body[0][1] >= level.dimensions[1]/2:
                level.blocks.extend(list(map(lambda x: Block(x), (filter(lambda x: x != snake.body[0], snake.body)))))
                snakes_collided.append(snake)
        # check snake collision
        for snake in level.snakes:
            for o_snake in level.snakes:
                if snake == o_snake:
                    if snake.body[0] in snake.body[1:]:
                        level.blocks.extend(list(map(lambda x: Block(x), snake.body[1:])))
                        snakes_collided.append(snake)
                else: # not self duhh
                    # head to head
                    if snake.body[0] in o_snake.body:
                        if snake.body[0] == o_snake.body[0] or \
                                (snake.body[0] == o_snake.body[1] and snake.body[1] == o_snake.body[0]):
                            if len(snake.body) == 2 and len(o_snake.body) > 2:
                                if snake not in snakes_collided:
                                    snakes_collided.append(snake)
                            elif len(o_snake.body) == 2 and len(snake.body) > 2:
                                if o_snake not in snakes_collided:
                                    snakes_collided.append(o_snake)
                            else:
                                level.blocks.extend(list(map(lambda x: Block(x),
                                                             (filter(lambda x: x != snake.body[0], snake.body[:-1])))))
                                level.blocks.extend(
                                    list(map(lambda x: Block(x), (filter(lambda x: x, o_snake.body[:-1])))))
                                if snake not in snakes_collided:
                                    snakes_collided.append(snake)
                                if o_snake not in snakes_collided:
                                    snakes_collided.append(o_snake)
                        else:  # head to something diff
                            if (len(snake.body) - 1)/(len(o_snake.body) - 1) > self.eat_percent:
                                cut_blocks = list(map(lambda x: Block(x), (filter(lambda x: x != snake.body[0],
                                                            o_snake.body[o_snake.body.index(snake.body[0])+1:]))))
                                level.blocks.extend(cut_blocks)
                                o_snake.body = o_snake.body[:o_snake.body.index(snake.body[0]) + 1]
                                snake.score += len(cut_blocks) + 1
                            else:
                                #cant eat, to low
                                level.blocks.extend(
                                    list(map(lambda x: Block(x),
                                             (filter(lambda x: x, snake.body[1:])))))
                                if snake not in snakes_collided:
                                    snakes_collided.append(snake)

        for dead_snake in snakes_collided:
            level.snakes.remove(dead_snake)
            dead_snake.score *= 0.7

        for snake in level.snakes:
            if snake.body[0] in list(map(lambda x: x.position, level.apples)):
                snake.score += 1
                apple_pop_i = None
                for ind, apple in enumerate(level.apples):
                    if apple.position == snake.body[0]:
                        apple_pop_i = ind
                level.apples.pop(apple_pop_i)
            else:
                snake.body.pop()
                if self.snake_poop[snake.id] and len(snake.body) > 1:
                    self.level.blocks.append(Block(snake.body.pop()))
コード例 #7
0
ファイル: wumbo.py プロジェクト: JasonDavidoff85/wumboCoin
 def __init__(self, privKey=None):
     self.crypto = Crypto(privKey)
     # set current block
     self.block = Block(self, 'blockchain/current.wub')