Example #1
0
def replace_keypair():
    if request.method == 'POST':

        if session.get('username') is None:
            return render_template('fileproof/message.html',
                                   message="user name is not in session.")

        if session.get('password_digest_str') is None:
            return render_template('fileproof/message.html',
                                   message="password is not in session.")

        r = requests.post(PREFIX_API + '/api/new-keypair',
                          json={
                              'username': session['username'],
                              'password_digest_str':
                              session['password_digest_str']
                          })
        res = r.json()

        if r.status_code != 200:
            return render_template('fileproof/message.html',
                                   message="Failed to replace keypair.")

        public_key = bbclib.convert_idstring_to_bytes(res['public_key_str'])
        private_key = bbclib.convert_idstring_to_bytes(res['private_key_str'])
        save_keypair(bbclib.Keypair(privkey=private_key, pubkey=public_key))

        return render_template('fileproof/message.html',
                               message="Keypair was replaced successfully.")
Example #2
0
def signup():
    if request.method == 'GET':
        return render_template('fileproof/sign-up.html')

    elif request.method == 'POST':

        r = requests.get(PREFIX_API + '/api/domain')
        res = r.json()

        if r.status_code != 200:
            return render_template(
                'fileproof/message.html',
                message="ERROR: Failed to connect core node to domain(%s)." %
                res['domain_id'])

        password = request.form.get('password')
        if password is None or len(password) <= 0:
            return render_template('fileproof/message.html',
                                   message="ERROR: Password is missing.")
        password_digest = bbclib.get_new_id(password, include_timestamp=False)
        password_digest_str = bbclib.convert_id_to_string(password_digest)

        username = request.form.get('username')
        if username is None or len(username) <= 0:
            return render_template('fileproof/message.html',
                                   message='ERROR: User name is missing.')

        r = requests.post(PREFIX_API + '/api/user',
                          json={
                              'password_digest_str': password_digest_str,
                              'username': username
                          })
        res = r.json()

        if r.status_code != 200:
            return render_template('fileproof/message.html',
                                   message=res['message'])

        public_key = bbclib.convert_idstring_to_bytes(res['public_key_str'])
        private_key = bbclib.convert_idstring_to_bytes(res['private_key_str'])

        with open(PRIVATE_KEY, "wb") as fout:
            fout.write(private_key)

        with open(PUBLIC_KEY, "wb") as fout:
            fout.write(public_key)

        return redirect('/fileproof/sign-in')
Example #3
0
def verify_file():

    if request.method == 'GET':

        asset_id_str = request.args.get('asset_id_str')
        asset_id = bbclib.convert_idstring_to_bytes(asset_id_str)

        asset_group_id_str = request.args.get('asset_group_id_str')
        asset_group_id = bbclib.convert_idstring_to_bytes(asset_group_id_str)

        user_id_str = request.args.get('user_id_str')
        user_id = bbclib.convert_idstring_to_bytes(user_id_str)

        bbc_app_client = setup_bbc_client(domain_id, user_id)

        ret = bbc_app_client.search_transaction_with_condition(
            asset_group_id=asset_group_id, asset_id=asset_id, user_id=user_id)
        assert ret

        response_data = bbc_app_client.callback.synchronize()
        if response_data[KeyType.status] < ESUCCESS:
            return jsonify(message="ERROR: %s" %
                           response_data[KeyType.reason].decode('utf-8')), 404

        transactions = [
            bbclib.deserialize(data)
            for data in response_data[KeyType.transactions]
        ]

        transaction, fmt = transactions[0]

        digest = transaction.digest()
        if not transaction.signatures[0].verify(digest):
            return jsonify(
                message="ERROR: Transaction digest is invalid."), 404

        if get_asset_file(transaction, response_data) is not None:
            data = get_asset_file(transaction, response_data)
        else:
            data = get_asset_body(transaction)

        file_digest = hashlib.sha256(data).digest()
        if file_digest == transaction.relations[0].asset.asset_file_digest:
            return jsonify(), 200
        else:
            return jsonify(message="ERROR: Asset file digest is invalid."), 404
Example #4
0
def update_file():

    if session.get('username') is None:
        return redirect('/fileproof/sign-in')

    if request.method == 'GET':
        return render_template('fileproof/store_file.html',
                               action='/fileproof/update')

    elif request.method == 'POST':

        file = request.files.getlist('files')[0]
        if file and allowed_file(file.filename):
            data = file.read()
            data_non_bytes = binascii.b2a_hex(data).decode('utf-8')
            filename = secure_filename(file.filename)
            filepath = './' + filename  #FIXME specific data directory is needed

        else:
            return render_template(
                'fileproof/message.html',
                message='ERROR: file must be selected and allowed file type.')

        fileinfo = get_id_from_mappings(os.path.basename(filepath),
                                        asset_group_id)
        if fileinfo is None:
            return render_template('fileproof/message.html',
                                   message="ERROR: %s is already existed." %
                                   file.filename)

        user_info = "Owner is %s" % session['username']

        transaction_id = fileinfo['transaction_id']
        transaction_id_str = bbclib.convert_id_to_string(transaction_id)

        public_key, private_key = load_keypair()

        r = requests.post(PREFIX_API + '/api/file',
                          json={
                              'asset_body':
                              user_info,
                              'asset_file':
                              data_non_bytes,
                              'asset_group_id_str':
                              asset_group_id_str,
                              'private_key_str':
                              bbclib.convert_id_to_string(private_key),
                              'public_key_str':
                              bbclib.convert_id_to_string(public_key),
                              'tx_id_str':
                              transaction_id_str,
                              'user_id_str':
                              session['user_id_str']
                          })

        res = r.json()

        if r.status_code != 200:
            return render_template('fileproof/message.html',
                                   message=res['message'])

        asset_ids = bbclib.convert_idstring_to_bytes(res['asset_ids_str'])
        transaction_id = bbclib.convert_idstring_to_bytes(
            res['transaction_id_str'])
        store_id_mappings(os.path.basename(filepath),
                          asset_group_id,
                          transaction_id=transaction_id,
                          asset_ids=asset_ids)

        message = "File update was success.\n"
        message += "asset_ids: %s \n" % res['asset_ids_str']
        message += "transaction_id: %s \n" % res['transaction_id_str']

        return render_template('fileproof/message.html', message=message)
Example #5
0
    def create_domain(self, domain_id=ZEROS, config=None):
        """Create domain and register user in the domain

        Args:
            domain_id (bytes): target domain_id to create
            config (dict): configuration for the domain
        Returns:
            bool:
        """
        if domain_id in self.domains:
            return False

        conf = self.config.get_domain_config(domain_id, create_if_new=True)
        if config is not None:
            conf.update(config)
        if 'node_id' not in conf or conf['node_id'] == "":
            node_id = bbclib.get_random_id()
            conf['node_id'] = bbclib.convert_id_to_string(node_id)
            self.config.update_config()
        else:
            node_id = bbclib.convert_idstring_to_bytes(conf.get('node_id'))

        self.domains[domain_id] = dict()
        self.domains[domain_id]['node_id'] = node_id
        self.domains[domain_id]['name'] = node_id.hex()[:4]
        self.domains[domain_id]['neighbor'] = NeighborInfo(
            network=self,
            domain_id=domain_id,
            node_id=node_id,
            my_info=self._get_my_nodeinfo(node_id))
        self.domains[domain_id]['topology'] = TopologyManagerBase(
            network=self,
            domain_id=domain_id,
            node_id=node_id,
            logname=self.logname,
            loglevel=self.loglevel)
        self.domains[domain_id]['user'] = UserMessageRouting(
            self, domain_id, logname=self.logname, loglevel=self.loglevel)
        self.get_domain_keypair(domain_id)

        workingdir = self.config.get_config()['workingdir']
        if domain_id == ZEROS:
            self.domains[domain_id]['data'] = DataHandlerDomain0(
                self,
                domain_id=domain_id,
                logname=self.logname,
                loglevel=self.loglevel)
            self.domain0manager = Domain0Manager(self,
                                                 node_id=node_id,
                                                 logname=self.logname,
                                                 loglevel=self.loglevel)
        else:
            self.domains[domain_id]['data'] = DataHandler(
                self,
                config=conf,
                workingdir=workingdir,
                domain_id=domain_id,
                logname=self.logname,
                loglevel=self.loglevel)

        self.domains[domain_id]['repair'] = RepairManager(
            self,
            domain_id,
            workingdir=workingdir,
            logname=self.logname,
            loglevel=self.loglevel)

        if self.domain0manager is not None:
            self.domain0manager.update_domain_belong_to()
            for dm in self.domains.keys():
                if dm != ZEROS:
                    self.domains[dm]['neighbor'].my_info.update(domain0=True)
            self.domains[domain_id]['topology'].update_refresh_timer_entry(1)
        self.stats.update_stats_increment("network", "num_domains", 1)
        self.logger.info("Domain %s is created" % (domain_id.hex()))
        return True
    def parse_arguments(self):

        self.argparser.add_argument('-4', '--ip4address', type=str,
                default="127.0.0.1", help='bbc_core IP address (IPv4)')
        self.argparser.add_argument('-6', '--ip6address', type=str,
                help='bbc_core IP address (IPv6)')
        self.argparser.add_argument('-c', '--config', type=str,
                default=bbc_config.DEFAULT_CONFIG_FILE,
                help='config file name')
        self.argparser.add_argument('-cp', '--coreport', type=int,
                default=bbc_config.DEFAULT_CORE_PORT,
                help='port number of bbc_core')
        self.argparser.add_argument('-d', '--domain_id', type=str,
                default=None,
                help='domain_id in hexadecimal')
        self.argparser.add_argument('-k', '--node_key', type=str,
                default=None,
                help='path to node key pem file')
        self.argparser.add_argument('-v', '--version', action='store_true',
                help='print version and exit')
        self.argparser.add_argument('-w', '--workingdir', type=str,
                default=bbc_config.DEFAULT_WORKING_DIR,
                help='working directory name')

        # config_demo command
        self.subparsers.add_parser('config_demo',
                help='Create a demo domain and config_tree (common command)')

        # config_tree command
        parser = self.subparsers.add_parser('config_tree',
                help='Configure how to form Merkle trees (common command)')
        parser.add_argument('transactions', type=int, action='store',
                help='# of transactions to wait before forming a Merkle tree')
        parser.add_argument('seconds', type=int, action='store',
                help='# of seconds to wait before forming a Merkle tree')

        # disable command
        self.subparsers.add_parser('disable',
                help='Disable ledger subsystem (common command)')

        # enable command
        self.subparsers.add_parser('enable',
                help='Enable ledger subsystem (common command)')

        # register_demo command
        parser = self.subparsers.add_parser('register_demo',
                help="Register dummy transaction_id's (common command)")
        parser.add_argument('count', type=int, action='store',
                help="# of dummy transaction_id's to register "
                "for testing/demo")

        # verify command
        parser = self.subparsers.add_parser('verify',
                help='Verify a transaction (common command)')
        parser.add_argument('txid', action='store',
                help='transaction_id to verify (in hexadecimal)')

        self._add_additional_arguments()

        args = self.argparser.parse_args()

        if args.version:
            print(self.tool + ' ' + self.version)
            sys.exit(0)

        if args.domain_id:
            self.domain_id = bbclib.convert_idstring_to_bytes(args.domain_id)

        if args.node_key and os.path.exists(args.node_key):
            self._run_client(args)
            self.client.set_node_key(args.node_key)

        if args.command_type == 'enable':
            self._run_client(args)
            self._enable()
            sys.exit(0)

        if args.command_type == 'disable':
            self._run_client(args)
            self._disable()
            sys.exit(0)

        if args.command_type == 'verify':
            self._run_client(args)
            self._verify(args, bbclib.convert_idstring_to_bytes(args.txid))
            sys.exit(0)

        if args.command_type == 'config_tree':
            self._check_domain_id()
            self._config_tree(args)
            sys.exit(0)

        if args.command_type == 'config_demo':
            self.domain_id = bbclib.get_new_id("dummy_domain")
            self._run_client(args)
            self._config_demo(args)
            sys.exit(0)

        if args.command_type == 'register_demo':
            self._run_client(args)
            self._register_demo(args.count)
            sys.exit(0)

        return args
Example #7
0
    elif parsed_args.command_type == "def-user":
        define_user(name=parsed_args.user_name, dic_users=dic_users)

    elif parsed_args.command_type == "issue":
        issue_to_user(name=parsed_args.user_name,
                      description=parsed_args.description,
                      dic_services=dic_services,
                      dic_users=dic_users)

    elif parsed_args.command_type == "new-keypair":
        replace_keypair(name=parsed_args.user_name,
                        dic=dic_users,
                        file_name=F_JSON_USERS)

    elif parsed_args.command_type == "redeem":
        redeem_from_user(ticket_id=bbclib.convert_idstring_to_bytes(
            parsed_args.ticket_id),
                         dic_services=dic_services,
                         dic_users=dic_users)

    if parsed_args.command_type == "service":
        if parsed_args.name is None:
            list_users(dic=dic_services)
        else:
            select_user(name=parsed_args.name,
                        dic=dic_services,
                        file_name=F_JSON_SERVICES)

    elif parsed_args.command_type == "setup":
        setup()

    elif parsed_args.command_type == "status":
Example #8
0
def get_transactions():

    if request.method == 'GET':

        asset_id_str = request.args.get('asset_id_str')
        if asset_id_str is not None:
            asset_id = bbclib.convert_idstring_to_bytes(asset_id_str)
        else:
            asset_id = None

        asset_group_id_str = request.args.get('asset_group_id_str')
        if asset_group_id_str is not None:
            asset_group_id = bbclib.convert_idstring_to_bytes(
                asset_group_id_str)
        else:
            asset_group_id = None

        count = request.args.get('count')
        if count is None:
            count = 0

        direction = request.args.get('direction')
        if direction is None:
            direction = 0

        start_from = request.args.get('start_from')
        if start_from is None:
            start_from = None

        until = request.args.get('until')
        if until is None:
            until = None

        user_id_search_str = request.args.get('user_id_search_str')
        if user_id_search_str is not None:
            user_id_search = bbclib.convert_idstring_to_bytes(
                user_id_search_str)
        else:
            user_id_search = None

        user_id_str = request.args.get('user_id_str')
        user_id = bbclib.convert_idstring_to_bytes(user_id_str)

        bbc_app_client = setup_bbc_client(domain_id, user_id)

        ret = bbc_app_client.search_transaction_with_condition(
            asset_group_id=asset_group_id, asset_id=asset_id, user_id=user_id)
        assert ret

        response_data = bbc_app_client.callback.synchronize()
        if response_data[KeyType.status] < ESUCCESS:
            return jsonify(message="ERROR: %s" %
                           response_data[KeyType.reason].decode('utf-8')), 404

        transactions = [
            bbclib.deserialize(data)
            for data in response_data[KeyType.transactions]
        ]

        dics = []
        for tx_tuple in transactions:
            tx, fmt_type = tx_tuple
            dics.append({
                'transaction_id':
                bbclib.convert_id_to_string(tx.transaction_id),
                'asset_group_id':
                bbclib.convert_id_to_string(tx.relations[0].asset_group_id),
                'asset_id':
                bbclib.convert_id_to_string(tx.relations[0].asset.asset_id),
                'user_id':
                bbclib.convert_id_to_string(tx.relations[0].asset.user_id),
                'timestamp':
                datetime.fromtimestamp(tx.timestamp / 1000)
            })

        return jsonify(transactions=dics), 200
Example #9
0
def store_file():

    if request.method == 'GET':

        asset_id_str = request.args.get('asset_id_str')
        asset_id = bbclib.convert_idstring_to_bytes(asset_id_str)

        asset_group_id_str = request.args.get('asset_group_id_str')
        asset_group_id = bbclib.convert_idstring_to_bytes(asset_group_id_str)

        user_id_str = request.args.get('user_id_str')
        user_id = bbclib.convert_idstring_to_bytes(user_id_str)

        bbc_app_client = setup_bbc_client(domain_id, user_id)

        ret = bbc_app_client.search_transaction_with_condition(
            asset_group_id=asset_group_id, asset_id=asset_id, user_id=user_id)
        assert ret

        response_data = bbc_app_client.callback.synchronize()
        if response_data[KeyType.status] < ESUCCESS:
            return jsonify(message="ERROR: %s" %
                           response_data[KeyType.reason].decode('utf-8')), 404

        transactions = [
            bbclib.deserialize(data)
            for data in response_data[KeyType.transactions]
        ]
        get_transaction, fmt_type = transactions[0]

        if KeyType.all_asset_files in response_data:
            asset_file_dict = response_data[KeyType.all_asset_files]
            asset_id = get_transaction.relations[0].asset.asset_id
            data = asset_file_dict[asset_id]

        else:
            data = get_transaction.relations[0].asset.asset_body

        return jsonify({
            'file': binascii.b2a_hex(data).decode('utf-8'),
            'message': None,
            'status': 'success'
        })

    elif request.method == 'POST':
        asset_body = request.json.get('asset_body')

        asset_file = request.json.get('asset_file')
        asset_file_bytes = binascii.a2b_hex(asset_file)

        asset_group_id_str = request.json.get('asset_group_id_str')
        asset_group_id = bbclib.convert_idstring_to_bytes(asset_group_id_str)

        private_key_str = request.json.get('private_key_str')
        private_key = bbclib.convert_idstring_to_bytes(private_key_str)

        public_key_str = request.json.get('public_key_str')
        public_key = bbclib.convert_idstring_to_bytes(public_key_str)

        keypair = bbclib.KeyPair(privkey=private_key, pubkey=public_key)

        tx_id_str = request.json.get('tx_id_str')
        if tx_id_str is not None:
            tx_id = bbclib.convert_idstring_to_bytes(tx_id_str)
        else:
            tx_id = None

        user_id_str = request.json.get('user_id_str')
        user_id = bbclib.convert_idstring_to_bytes(user_id_str)

        asset_ids, transaction_id, message = \
            store_proc(asset_body, asset_file_bytes, asset_group_id,
                domain_id, keypair, user_id, txid=tx_id)

        if message is not None:
            return jsonify(message=message), 404

        if asset_ids is None:
            return jsonify(message="ERROR: asset_id is not found"), 404

        if transaction_id is None:
            return jsonify(message="ERROR: transaction_id is not found"), 404

        return jsonify(asset_ids_str=bbclib.convert_id_to_string(asset_ids),
                       transaction_id_str=bbclib.convert_id_to_string(
                           transaction_id)), 200
Example #10
0
    parsed_args = argument_parser()
    addr = "127.0.0.1"
    if parsed_args.ip4address:
        addr = parsed_args.ip4address
    if parsed_args.ip6address:
        addr = parsed_args.ip6address
    port = parsed_args.port

    bbcclient = bbc_app.BBcAppClient(host=addr,
                                     port=port,
                                     multiq=False,
                                     loglevel="all")
    if os.path.exists(parsed_args.node_key):
        bbcclient.set_node_key(parsed_args.node_key)

    domain_id = bbclib.convert_idstring_to_bytes(parsed_args.domain_id)
    query_id = bbcclient.domain_setup(domain_id)
    dat = bbcclient.callback.synchronize()
    assert dat[KeyType.status] == ESUCCESS

    send_domain_ping(bbcclient, domain_id, parsed_args.dst_address,
                     parsed_args.dst_port)

    print("*** wait 5 sec, checking neighbor list in the core ***")
    time.sleep(5)
    query_id = bbcclient.get_domain_neighborlist(domain_id=domain_id)
    dat = bbcclient.callback.synchronize()
    print("====== neighbor list =====")
    for k in range(len(dat)):
        node_id, ipv4, ipv6, port, domain0 = dat[k]
        if k == 0: