Exemplo n.º 1
0
        memetx.generate_genesis_hashlink()
        memetx.txid = genesis_meme.genesis_txid

        Validate(memetx,
                 db=db,
                 ipfs_dir=config['DATA_DIR'],
                 prev_block_memes=[],
                 sync=True,
                 genesis=True)
        # Add genesis meme to database

        db.add_meme(
            **{
                "ipfs_id": genesis_meme.get_ipfs_id(),
                "hashlink": genesis_meme.get_hashlink(),
                "txid": genesis_meme.genesis_txid,
                "author": genesis_meme.genesis_author,
                "block": genesis_meme.genesis_kekcoin_block,
                "imgformat": genesis_meme.genesis_img_format,
                "status": "confirm"
            })

        # Sync loop
        if genesis_meme.genesis_kekcoin_block < block_height:
            block = genesis_meme.genesis_kekcoin_block + 1
            max_errors = 0
            while block < block_height + 1:
                try:
                    sync_block(db, block)
                except IOError as e:
                    logger.error(
                        'COMMAND %s Failed %s: %s' %
Exemplo n.º 2
0
    def on_post(self, req, resp):
        logger.info('COMMAND %s Received' % self.__class__.__name__)
        db = MemeChainDB(os.path.join(config['DATA_DIR'], 'memechain.json'))

        while check_running():
            time.sleep(3)
            logger.info('Waiting for the synchronization process to complete add_meme')


        # Generate random placeholder img name
        img_placeholder_name = str(random.random()).split(".")[1]

        ext = mimetypes.guess_extension(req.content_type)
        if ext == '.jpe':
            ext = '.jpg'


        name = '{img_name}{ext}'.format(img_name=img_placeholder_name, ext=ext)
        image_path = os.path.join(config['DATA_DIR'], name)


        # Write image to local storage
        with io.open(image_path, 'wb') as image_file:
            while True:
                chunk = req.stream.read(self._CHUNK_SIZE_BYTES)
                if not chunk:
                    break

                image_file.write(chunk)


        if magic.from_file(image_path).lower().find(mimetypes.guess_extension(req.content_type)[1:]) < 0:
            raise falcon.HTTPBadRequest( "Memechain error",
                                   "Meme has not passed validation, file extension is wrong.")


        # Check file size
        meme_filesize = os.path.getsize(image_path) * 0.000001 # in MB

        if meme_filesize > 10:
            os.remove(image_path)
            
            logger.error('COMMAND %s Failed %s: %s'
                         % (self.__class__.__name__, 'Upload Error',
                            "Meme filesize too large."))
            raise falcon.HTTPError(falcon.HTTP_400, "Upload error",
                                   "Meme filesize too large.")

        # Add image to ipfs
        ipfs_id = IPFSTools().add_meme(image_path)['Hash']
        # Rename local img file to ipfs_id for easy reference
        new_name = '{img_name}{ext}'.format(img_name=ipfs_id, ext=ext)
        os.rename(image_path, os.path.join(config['DATA_DIR'], new_name))
        # Add to Kekcoin chain
        memetx = MemeTx(ipfs_id)
        prev_block_memes = db.get_prev_block_memes()

        if prev_block_memes:
            memetx.generate_hashlink(prev_block_memes)
            try:
                Validate(memetx, db=db, ipfs_dir=config['DATA_DIR'],
                         prev_block_memes=prev_block_memes)
            
            except TypeError as e:
                # Delete invalid Meme
                os.remove(os.path.join(config['DATA_DIR'], new_name))

                logger.error('COMMAND %s Failed %s: %s'
                             % (self.__class__.__name__, 'Memechain Error',
                                "Meme has not passed memechain validation, file extension not supported.%s") )
                raise falcon.HTTPError(falcon.HTTP_400, "Memechain error",
                                       "Meme has not passed validation, file extension not supported.%s" % e )

            if memetx.is_meme_valid():


                memetx.blockchain_write()

                db.add_meme(**{"ipfs_id": ipfs_id, "hashlink": memetx.get_hashlink(),
                               "txid": memetx.get_txid(), "author": memetx.get_author(), "block": 0, "imgformat": ext[1:],
                               "status": "unconfirm"})
                resp.status = falcon.HTTP_201
                resp.set_header('Powered-By', 'Memechain')

                logger.info('COMMAND %s Success' % self.__class__.__name__)
                resp.body = json.dumps({
                    'success': True,
                    'result': {'ipfs_id' : ipfs_id, 'txid' : memetx.get_txid(), 'hashlink' : memetx.get_hashlink(), 'author' : memetx.get_author()}})

            else:
                # Delete invalid Meme
                os.remove(os.path.join(config['DATA_DIR'], new_name))

                logger.error('COMMAND %s Failed %s: %s'
                             % (self.__class__.__name__, 'Memechain Error',
                                "Meme has not passed memechain validation: "))
                raise falcon.HTTPError(falcon.HTTP_400, "Memechain error",
                                       "Meme has not passed validation: ")
        else:
            # Genesis block logic
            memetx = MemeTx(ipfs_id)
            memetx.generate_genesis_hashlink()

            memetx.blockchain_write()

            resp.status = falcon.HTTP_201
            resp.set_header('Powered-By', 'Memechain')

            logger.info('COMMAND %s Success' % self.__class__.__name__)
            resp.body = json.dumps({
                'success': True,
                'result': {'ipfs_id' : ipfs_id, 'txid' : memetx.get_txid(), 'hashlink' : memetx.get_hashlink(), 'author' : memetx.get_author()}})