Example #1
0
def test_vote_proposal(node, account, wif, subject):
    logger.info("Testing: vote_proposal")
    s = Hive(node=[node], no_broadcast=False, keys=[wif])
    # first we will find our special proposal and get its proposal_id
    proposals = s.rpc.list_proposals([account], 1000, "by_creator",
                                     "ascending", "inactive")

    found = None
    for proposal in proposals:
        if proposal["subject"] == subject:
            found = proposal

    assert found is not None
    proposal_id = int(found["proposal_id"])

    # now lets vote
    from beembase.operations import Update_proposal_votes
    op = Update_proposal_votes(**{
        "voter": account,
        "proposal_ids": [proposal_id],
        "approve": True
    })

    ret = None
    try:
        ret = s.finalizeOp(op, account, "active")
    except Exception as ex:
        logger.exception("Exception: {}".format(ex))
        raise ex

    assert ret["operations"][0][1]["voter"] == account
    assert ret["operations"][0][1]["proposal_ids"][0] == proposal_id
    assert ret["operations"][0][1]["approve"] == True
    hive_utils.common.wait_n_blocks(s.rpc.url, 2)
Example #2
0
class ProposalsCreatorThread(threading.Thread):
    def __init__(self, node_url, proposals, private_key, delay):
        threading.Thread.__init__(self)
        self.node_url = node_url
        self.proposals = proposals
        self.private_key = private_key
        self.delay = delay
        self.log = logging.getLogger(MODULE_NAME + ".ProposalsCreatorThread." +
                                     self.node_url)
        self.node_client = Hive(node=[self.node_url], keys=[self.private_key])

    def run(self):
        self.log.info("Sending proposals to node at: {} with delay {}".format(
            self.node_url, self.delay))
        sleep(self.delay)
        from beembase.operations import Create_proposal
        for proposal in self.proposals:
            self.log.info("New proposal ==> ({},{},{},{},{},{},{})".format(
                proposal['creator'], proposal['receiver'],
                proposal['start_date'], proposal['end_date'],
                proposal['daily_pay'], proposal['subject'],
                proposal['permlink']))
            op = Create_proposal(
                **{
                    'creator': proposal['creator'],
                    'receiver': proposal['receiver'],
                    'start_date': proposal['start_date'],
                    'end_date': proposal['end_date'],
                    'daily_pay': proposal['daily_pay'],
                    'subject': proposal['subject'],
                    'permlink': proposal['permlink']
                })
            self.node_client.finalizeOp(op, proposal['creator'], "active")
Example #3
0
def test_update_proposal(node, creator, wif):
    logger.info("Testing: update_proposal")
    s = Hive(node=[node], no_broadcast=False, keys=[wif])
    proposals = s.rpc.list_proposals([creator], 1000, "by_creator",
                                     "ascending", "all")
    print(proposals[0])
    from beembase.operations import Update_proposal
    subject = "Some new proposal subject"
    op = Update_proposal(
        **{
            'proposal_id': proposals[0]["proposal_id"],
            'creator': proposals[0]["creator"],
            'daily_pay': "16.000 TBD",
            'subject': subject,
            'permlink': proposals[0]["permlink"]
        })
    try:
        s.finalizeOp(op, creator, "active")
    except Exception as ex:
        logger.exception("Exception: {}".format(ex))
        raise ex
    hive_utils.common.wait_n_blocks(node, 3)

    proposals = s.rpc.list_proposals([creator], 1000, "by_creator",
                                     "ascending", "all")
    print(proposals[0])
    assert proposals[0]["subject"] == subject, "Subjects dont match"
Example #4
0
def send_notification(custom_json, server_account='', wif=''):
    """ Sends a custom_json to Hive
        Expects two env variables, Hive account name and posting key
        HIVE_SERVER_ACCOUNT
        HIVE_POSTING_KEY
        """

    operation_id = 'hive-hydra'

    try:
        if server_account == '':
            server_account = os.getenv('HIVE_SERVER_ACCOUNT')
            pass
        if wif == '':
            wif = [os.getenv('HIVE_POSTING_KEY')]
            pass

        if USE_TEST_NODE:
            h = Hive(keys=wif,node=TEST_NODE)
        else:
            h = Hive(keys=wif)


        tx = h.custom_json(id=operation_id, json_data= custom_json,
                            required_posting_auths=[server_account])

        trx_id = tx['trx_id']
        logging.info(f'Transaction sent: {trx_id}')
        return trx_id, True

    except Exception as ex:
        error_message = f'{ex} occurred {ex.__class__}'
        logging.error(error_message)
        trx_id = error_message
        return trx_id, False
Example #5
0
 def test_create_account_password(self):
     bts = Hive(node=get_hive_nodes(),
                 nobroadcast=True,
                 unsigned=True,
                 data_refresh_time_seconds=900,
                 keys={"active": wif, "owner": wif2, "memo": wif3},
                 num_retries=10)
     core_unit = "STM"
     name = ''.join(random.choice(string.ascii_lowercase) for _ in range(12))
     key5 = PrivateKey()
     bts.txbuffer.clear()
     tx = bts.create_account(
         name,
         creator="test",   # 1.2.7
         password="******",
         additional_owner_keys=[format(key5.pubkey, core_unit)],
         additional_active_keys=[format(key5.pubkey, core_unit)],
         additional_posting_keys=[format(key5.pubkey, core_unit)],
         additional_owner_accounts=["test1"],  # 1.2.0
         additional_active_accounts=["test1"],
         storekeys=False,
     )
     if isinstance(tx["operations"][0], list):
         self.assertEqual(
             tx["operations"][0][0],
             "account_create"
         )
         op = tx["operations"][0][1]
     else:
         self.assertEqual(
             tx["operations"][0]["type"],
             "account_create_operation"
         )
         op = tx["operations"][0]["value"]        
     role = "active"
     self.assertIn(
         format(key5.pubkey, core_unit),
         [x[0] for x in op[role]["key_auths"]])
     self.assertIn(
         format(key5.pubkey, core_unit),
         [x[0] for x in op[role]["key_auths"]])
     self.assertIn(
         "test1",
         [x[0] for x in op[role]["account_auths"]])
     role = "owner"
     self.assertIn(
         format(key5.pubkey, core_unit),
         [x[0] for x in op[role]["key_auths"]])
     self.assertIn(
         format(key5.pubkey, core_unit),
         [x[0] for x in op[role]["key_auths"]])
     self.assertIn(
         "test1",
         [x[0] for x in op[role]["account_auths"]])
     self.assertEqual(
         op["creator"],
         "test")
Example #6
0
 def __init__(self, node_url, proposals, private_key, delay):
     threading.Thread.__init__(self)
     self.node_url = node_url
     self.proposals = proposals
     self.private_key = private_key
     self.delay = delay
     self.log = logging.getLogger(MODULE_NAME + ".ProposalsCreatorThread." +
                                  self.node_url)
     self.node_client = Hive(node=[self.node_url], keys=[self.private_key])
Example #7
0
 def test_create_account(self):
     bts = Hive(node=self.nodelist.get_hive_nodes(),
                nobroadcast=True,
                unsigned=True,
                data_refresh_time_seconds=900,
                keys={
                    "active": wif,
                    "owner": wif,
                    "memo": wif
                },
                num_retries=10)
     core_unit = "STM"
     name = ''.join(
         random.choice(string.ascii_lowercase) for _ in range(12))
     key1 = PrivateKey()
     key2 = PrivateKey()
     key3 = PrivateKey()
     key4 = PrivateKey()
     key5 = PrivateKey()
     bts.txbuffer.clear()
     tx = bts.create_account(
         name,
         creator="test",  # 1.2.7
         owner_key=format(key1.pubkey, core_unit),
         active_key=format(key2.pubkey, core_unit),
         posting_key=format(key3.pubkey, core_unit),
         memo_key=format(key4.pubkey, core_unit),
         additional_owner_keys=[format(key5.pubkey, core_unit)],
         additional_active_keys=[format(key5.pubkey, core_unit)],
         additional_posting_keys=[format(key5.pubkey, core_unit)],
         additional_owner_accounts=["test1"],  # 1.2.0
         additional_active_accounts=["test2"],
         additional_posting_accounts=["test3"],
         storekeys=False,
     )
     self.assertEqual(tx["operations"][0][0], "account_create")
     op = tx["operations"][0][1]
     role = "active"
     self.assertIn(format(key5.pubkey, core_unit),
                   [x[0] for x in op[role]["key_auths"]])
     self.assertIn(format(key5.pubkey, core_unit),
                   [x[0] for x in op[role]["key_auths"]])
     self.assertIn("test2", [x[0] for x in op[role]["account_auths"]])
     role = "posting"
     self.assertIn(format(key5.pubkey, core_unit),
                   [x[0] for x in op[role]["key_auths"]])
     self.assertIn(format(key5.pubkey, core_unit),
                   [x[0] for x in op[role]["key_auths"]])
     self.assertIn("test3", [x[0] for x in op[role]["account_auths"]])
     role = "owner"
     self.assertIn(format(key5.pubkey, core_unit),
                   [x[0] for x in op[role]["key_auths"]])
     self.assertIn(format(key5.pubkey, core_unit),
                   [x[0] for x in op[role]["key_auths"]])
     self.assertIn("test1", [x[0] for x in op[role]["account_auths"]])
     self.assertEqual(op["creator"], "test")
Example #8
0
 def setUpClass(cls):
     nodelist = NodeList()
     nodelist.update_nodes(steem_instance=Hive(node=nodelist.get_hive_nodes(), num_retries=10))
     cls.bts = Hive(
         node=nodelist.get_nodes(exclude_limited=True),
         nobroadcast=True,
         keys=[wif],
         num_retries=10
     )
     set_shared_steem_instance(cls.bts)
Example #9
0
 def setUpClass(cls):
     cls.nodelist = NodeList()
     cls.nodelist.update_nodes(steem_instance=Hive(node=cls.nodelist.get_hive_nodes(), num_retries=10))
     cls.bts = Hive(
         node=cls.nodelist.get_hive_nodes(),
         nobroadcast=True,
         unsigned=True,
         data_refresh_time_seconds=900,
         keys={"active": wif, "owner": wif2, "memo": wif3},
         num_retries=10)
     cls.account = Account("test", full=True, steem_instance=cls.bts)
Example #10
0
    def test_default_connection(self):
        nodelist = NodeList()
        nodelist.update_nodes(steem_instance=Hive(node=nodelist.get_hive_nodes(), num_retries=10))

        b2 = Hive(
            node=nodelist.get_hive_nodes(),
            nobroadcast=True,
        )
        set_shared_steem_instance(b2)
        bts = Account("beem")
        self.assertEqual(bts.blockchain.prefix, "STM")
Example #11
0
def test_create_proposal(node, creator_account, receiver_account, wif,
                         subject):
    logger.info("Testing: create_proposal")
    s = Hive(node=[node], no_broadcast=False, keys=[wif])

    import datetime
    now = datetime.datetime.now()

    start_date, end_date = test_utils.get_start_and_end_date(now, 10, 2)

    from beem.account import Account
    try:
        creator = Account(creator_account, hive_instance=s)
    except Exception as ex:
        logger.error("Account: {} not found. {}".format(creator_account, ex))
        raise ex

    try:
        receiver = Account(receiver_account, hive_instance=s)
    except Exception as ex:
        logger.error("Account: {} not found. {}".format(receiver_account, ex))
        raise ex

    ret = s.post("Hivepy proposal title",
                 "Hivepy proposal body",
                 creator["name"],
                 permlink="hivepy-proposal-title",
                 tags="proposals")
    from beembase.operations import Create_proposal
    op = Create_proposal(
        **{
            "creator": creator["name"],
            "receiver": receiver["name"],
            "start_date": start_date,
            "end_date": end_date,
            "daily_pay": "16.000 TBD",
            "subject": subject,
            "permlink": "hivepy-proposal-title"
        })
    ret = None
    try:
        ret = s.finalizeOp(op, creator["name"], "active")
    except Exception as ex:
        logger.exception("Exception: {}".format(ex))
        raise ex

    assert ret["operations"][0][1]["creator"] == creator["name"]
    assert ret["operations"][0][1]["receiver"] == receiver["name"]
    assert ret["operations"][0][1]["start_date"] == start_date
    assert ret["operations"][0][1]["end_date"] == end_date
    assert ret["operations"][0][1]["daily_pay"] == "16.000 TBD"
    assert ret["operations"][0][1]["subject"] == subject
    assert ret["operations"][0][1]["permlink"] == "hivepy-proposal-title"
Example #12
0
    def test_stm1stm2(self):
        nodelist = NodeList()
        nodelist.update_nodes(steem_instance=Hive(
            node=nodelist.get_hive_nodes(), num_retries=10))
        b1 = Steem(node="https://api.steemit.com",
                   nobroadcast=True,
                   num_retries=10)
        node_list = nodelist.get_hive_nodes()

        b2 = Hive(node=node_list, nobroadcast=True, num_retries=10)

        self.assertNotEqual(b1.rpc.url, b2.rpc.url)
Example #13
0
def test_list_proposals(node, account, wif, subject):
    logger.info("Testing: list_proposals")
    s = Hive(node=[node], no_broadcast=False, keys=[wif])
    # list inactive proposals, our proposal shoud be here
    proposals = s.rpc.list_proposals([account], 1000, "by_creator",
                                     "ascending", "inactive")
    found = None
    for proposal in proposals:
        if proposal["subject"] == subject:
            found = proposal

    assert found is not None

    # list active proposals, our proposal shouldnt be here
    proposals = s.rpc.list_proposals([account], 1000, "by_creator",
                                     "ascending", "active")
    found = None
    for proposal in proposals:
        if proposal["subject"] == subject:
            found = proposal

    assert found is None

    # list all proposals, our proposal should be here
    proposals = s.rpc.list_proposals([account], 1000, "by_creator",
                                     "ascending", "all")

    found = None
    for proposal in proposals:
        if proposal["subject"] == subject:
            found = proposal

    assert found is not None
Example #14
0
 def test_hive_nodes(self):
     nodelist = NodeList()
     nodelist.update_nodes()
     hive_nodes = nodelist.get_hive_nodes()
     for node in hive_nodes:
         blockchainobject = Hive(node=node)
         assert blockchainobject.is_hive
Example #15
0
    def setUpClass(cls):
        cls.bts = Hive(node=get_hive_nodes(),
                       nobroadcast=True,
                       keys={"active": wif},
                       num_retries=10)
        # from getpass import getpass
        # self.bts.wallet.unlock(getpass())
        set_shared_blockchain_instance(cls.bts)
        cls.bts.set_default_account("test")

        acc = Account("fullnodeupdate", blockchain_instance=cls.bts)
        n_votes = 0
        index = 0
        entries = acc.get_blog(limit=20)[::-1]
        while n_votes == 0:
            comment = Comment(entries[index], blockchain_instance=cls.bts)
            votes = comment.get_votes()
            n_votes = len(votes)
            index += 1

        last_vote = votes[0]

        cls.authorpermvoter = construct_authorpermvoter(
            last_vote['author'], last_vote['permlink'], last_vote["voter"])
        [author, permlink,
         voter] = resolve_authorpermvoter(cls.authorpermvoter)
        cls.author = author
        cls.permlink = permlink
        cls.voter = voter
        cls.authorperm = construct_authorperm(author, permlink)
Example #16
0
    def setUpClass(cls):
        stm = Hive(node=get_hive_nodes())
        stm.config.refreshBackup()
        stm.set_default_nodes(["xyz"])
        del stm

        cls.urls = get_hive_nodes()
        cls.bts = Hive(node=cls.urls, nobroadcast=True, num_retries=10)
        set_shared_steem_instance(cls.bts)
        acc = Account("fullnodeupdate", steem_instance=cls.bts)
        comment = Comment(acc.get_blog_entries(limit=5)[1],
                          steem_instance=cls.bts)
        cls.authorperm = comment.authorperm
        votes = comment.get_votes(raw_data=True)
        last_vote = votes[-1]
        cls.authorpermvoter = comment['authorperm'] + '|' + last_vote["voter"]
Example #17
0
 def test_history_op_filter2(self):
     stm = Hive("https://api.hive.blog")
     batch_size = 100
     account = Account("beembot", blockchain_instance=stm)
     votes_list = list(
         account.history(only_ops=["vote"], batch_size=batch_size))
     other_list = list(
         account.history(exclude_ops=["vote"], batch_size=batch_size))
     all_list = list(account.history(batch_size=batch_size))
     self.assertEqual(len(all_list), len(votes_list) + len(other_list))
     index = 0
     for h in sorted((votes_list + other_list), key=lambda h: h["index"]):
         self.assertEqual(index, h["index"])
         index += 1
     votes_list = list(
         account.history_reverse(only_ops=["vote"], batch_size=batch_size))
     other_list = list(
         account.history_reverse(exclude_ops=["vote"],
                                 batch_size=batch_size))
     all_list = list(account.history_reverse(batch_size=batch_size))
     self.assertEqual(len(all_list), len(votes_list) + len(other_list))
     index = 0
     for h in sorted((votes_list + other_list), key=lambda h: h["index"]):
         self.assertEqual(index, h["index"])
         index += 1
Example #18
0
 def setUpClass(cls):
     nodelist = NodeList()
     cls.bts = Hive(
         node=nodelist.get_hive_nodes(),
         nobroadcast=True,
         num_retries=10
     )
     set_shared_blockchain_instance(cls.bts)
Example #19
0
 def setUpClass(cls):
     node_list = get_hive_nodes()
     cls.stm = Hive(node=node_list,
                    keys={
                        "active": wif,
                        "owner": wif2,
                        "memo": wif3
                    },
                    nobroadcast=True,
                    num_retries=10)
     cls.steemit = Hive(node="https://api.steemit.com",
                        nobroadcast=True,
                        keys={
                            "active": wif,
                            "owner": wif2,
                            "memo": wif3
                        },
                        num_retries=10)
     set_shared_blockchain_instance(cls.stm)
     cls.stm.set_default_account("test")
Example #20
0
def main():
    load_config()
    load_users()

    nodelist = NodeList()
    nodelist.update_nodes()
    nodes = nodelist.get_hive_nodes()
    hive = Hive(wif=config['wif'])
    set_shared_hive_instance(hive)

    do_airdrop(hive)
Example #21
0
    def start(self, authorperm=None, file=None):
        self.main_window = Tk()
        self.main_window.title('HiveDiff')
        self.__main_window_ui = MainWindowUI(self.main_window)
        
        self.leftFile = ''
        self.rightFile = ''
        self.authorperm = ''

        self.__main_window_ui.center_window()
        self.__main_window_ui.create_file_path_labels()
        self.__main_window_ui.create_text_areas()
        self.__main_window_ui.create_search_text_entry(self.__findNext)
        self.__main_window_ui.create_line_numbers()
        self.__main_window_ui.create_scroll_bars()
        self.__main_window_ui.create_file_treeview()
        path_to_my_project = os.getcwd()
        self.__main_window_ui.add_menu('File', [
            {'name': 'Compare Markdown file', 'command': self.__browse_files},
            {'name': 'View Post history', 'command': self.__enter_post},
            {'name': 'Compare Markdown files in Directory', 'command': self.__browse_directories},
            {'name': 'Reload', 'command': self.__reload, 'accelerator': 'Ctrl+R'},
            {'separator'},
            {'name': 'Exit', 'command': self.__exit, 'accelerator': 'Alt+F4'}
            ])
        self.__main_window_ui.add_menu('Edit', [
            {'name': 'Find', 'command': self.__startFindText, 'accelerator': 'Ctrl+F'},
            {'separator'},
            {'name': 'Cut', 'command': self.__cut, 'accelerator': 'Ctrl+X'},
            {'name': 'Copy', 'command': self.__copy, 'accelerator': 'Ctrl+C'},
            {'name': 'Paste', 'command': self.__paste, 'accelerator': 'Ctrl+P'},
            {'separator'},
            {'name': 'Go To Line', 'command': self.__goToLine, 'accelerator': 'Ctrl+G'}
            ])
        self.__main_window_ui.add_menu('Help', [
            {'name': 'About', 'command': self.__about},
            ])
        self.__main_window_ui.fileTreeView.bind('<<TreeviewSelect>>', lambda *x:self.treeViewItemSelected())

        nodelist = NodeList()
        nodelist.update_nodes()
        hive = Hive(node=nodelist.get_hive_nodes())
        set_shared_blockchain_instance(hive)

        self.leftFile = ''
        self.rightFile = file if file else ''
        self.filesChanged()
        if authorperm != '' and authorperm is not None:
            self.authorperm = authorperm
            self.__resolve_authorperm()

        self.__bind_key_shortcuts()

        self.main_window.mainloop()
Example #22
0
    def setUpClass(cls):

        cls.bts = Hive(
            node=get_hive_nodes(),
            nobroadcast=True,
            bundle=False,
            unsigned=True,
            # Overwrite wallet to use this list of wifs only
            keys={"active": wif},
            num_retries=10)
        cls.account = Account("beembot", steem_instance=cls.bts)
        set_shared_blockchain_instance(cls.bts)
Example #23
0
def test_remove_proposal(node, account, wif, subject):
    logger.info("Testing: remove_proposal")
    s = Hive(node=[node], no_broadcast=False, keys=[wif])
    # first we will find our special proposal and get its proposal_id
    proposals = s.rpc.list_proposals([account], 1000, "by_creator",
                                     "ascending", "inactive")

    found = None
    for proposal in proposals:
        if proposal["subject"] == subject:
            found = proposal

    assert found is not None, "Not found"
    proposal_id = int(found["proposal_id"])

    # remove proposal
    print(account)
    from beembase.operations import Remove_proposal
    op = Remove_proposal(**{
        'voter': account,
        'proposal_owner': account,
        'proposal_ids': [proposal_id]
    })

    try:
        s.finalizeOp(op, account, "active")
    except Exception as ex:
        logger.exception("Exception: {}".format(ex))
        raise ex

    # try to find our special proposal
    proposals = s.rpc.list_proposals([account], 1000, "by_creator",
                                     "ascending", "inactive")

    found = None
    for proposal in proposals:
        if proposal["subject"] == subject:
            found = proposal

    assert found is None, "Not found"
Example #24
0
    def setUpClass(cls):
        nodelist = NodeList()
        nodelist.update_nodes(blockchain_instance=Hive(
            node=nodelist.get_hive_nodes(), num_retries=10))
        node_list = nodelist.get_hive_nodes()

        cls.bts = Hive(node=node_list,
                       use_condenser=True,
                       nobroadcast=True,
                       unsigned=True,
                       keys={"active": wif},
                       num_retries=10)

        acc = Account("fullnodeupdate", blockchain_instance=cls.bts)
        comment = Comment(acc.get_blog_entries(limit=5)[0],
                          blockchain_instance=cls.bts)
        cls.authorperm = comment.authorperm
        [author, permlink] = resolve_authorperm(cls.authorperm)
        cls.author = author
        cls.permlink = permlink
        cls.category = comment.category
        cls.title = comment.title
Example #25
0
def test_list_voter_proposals(node, account, wif, subject):
    logger.info("Testing: list_voter_proposals")
    s = Hive(node=[node], no_broadcast=False, keys=[wif])
    voter_proposals = s.rpc.list_proposal_votes([account], 1000,
                                                "by_voter_proposal",
                                                "ascending", "inactive")

    found = None
    for proposals in voter_proposals:
        if proposals["proposal"]["subject"] == subject:
            found = proposals

    assert found is not None
Example #26
0
def test_update_proposal(node, creator, wif):
    from beembase.operations import Update_proposal
    from datetime import timedelta
    import dateutil.parser
    s = Hive(node=[node], no_broadcast=False, keys=[wif])

    logger.info("Testing: update_proposal without updating the end date")
    proposals = s.rpc.list_proposals([creator], 1000, "by_creator",
                                     "ascending", "all")
    print(proposals[0])
    new_subject = "Some new proposal subject"
    new_daily_pay = "15.000 TBD"
    op = Update_proposal(
        **{
            'proposal_id': proposals[0]["proposal_id"],
            'creator': proposals[0]["creator"],
            'daily_pay': new_daily_pay,
            'subject': new_subject,
            'permlink': proposals[0]["permlink"]
        })
    try:
        s.finalizeOp(op, creator, "active")
    except Exception as ex:
        logger.exception("Exception: {}".format(ex))
        raise ex
    hive_utils.common.wait_n_blocks(node, 3)

    proposals = s.rpc.list_proposals([creator], 1000, "by_creator",
                                     "ascending", "all")
    print(proposals[0])
    assert proposals[0]["subject"] == new_subject, "Subjects dont match"
    assert proposals[0]["daily_pay"] == new_daily_pay, "daily pay dont match"

    logger.info("Testing: update_proposal and updating the end date")
    end_date = test_utils.date_to_iso(
        dateutil.parser.parse(proposals[0]['end_date']) - timedelta(days=1))

    op = Update_proposal(
        **{
            'proposal_id': proposals[0]["proposal_id"],
            'creator': proposals[0]["creator"],
            'daily_pay': "15.000 TBD",
            'subject': new_subject,
            'prefix': "TST",
            'permlink': proposals[0]["permlink"],
            'end_date': end_date
        })
    try:
        s.finalizeOp(op, creator, "active")
    except Exception as ex:
        logger.exception("Exception: {}".format(ex))
        raise ex
    hive_utils.common.wait_n_blocks(node, 3)

    proposals = s.rpc.list_proposals([creator], 1000, "by_creator",
                                     "ascending", "all")
    print(proposals[0])
    assert proposals[0]["end_date"] == end_date, "End date doesn't match"
    def analyze_activity(self):
        for comment in self.account.history_reverse(
                only_ops=['comment', 'vote']):
            if comment['type'] == 'vote':
                # Votes by himself
                if comment['voter'] == self.username and comment[
                        'voter'] != comment['author']:
                    # If I am the voter and it is not my post
                    c = Comment(f"@{comment['author']}/{comment['permlink']}",
                                blockchain_instance=Hive())

                    # vectorize
                    _input = WordEmbedding.vectorize_text(
                        model=config.statics.Word2Vec,
                        html=c.body,
                        text=c.title + ". ")
                    if _input is None:
                        continue

                    _output = config.statics.TextCNN(_input).cpu()
                    self.add_categories(_output)
                else:
                    # Goto start --> No wait
                    continue

            if comment['type'] == 'comment':
                # Post or comment
                if comment['author'] != self.username:
                    # Activity, he does not (Someone else commented at his blog...)
                    continue

                _input = WordEmbedding.vectorize_text(
                    model=config.statics.Word2Vec,
                    html=comment['body'],
                    text=comment['title'] + ". ")
                if _input is None:
                    # To less words or Error
                    continue

                _output = config.statics.TextCNN(_input).cpu()
                self.add_categories(_output)

            if self.data_length >= config.PROFILER_MIN_DATA:
                # make brake
                time.sleep(0.75)
            if self.data_length >= config.PROFILER_MAX_DATA:
                break

        self.finished = True
        self.update()
    def __init__(self, username: str, start_get_post_thread=True):
        self.username = username
        self.account = Account(username, blockchain_instance=Hive())

        mysql_con = config.get_connection()
        if mysql_con is None:
            print(
                "[INFO] Can't start Latest Post Manager because of an mysql database error!"
            )
            return

        result = database.read_query(
            "SELECT * FROM profiler WHERE username=%s;", (username, ),
            con=mysql_con,
            close_con=False)
        if len(result) == 0:
            # No profiler exists, create one
            self.category = [0 for i in config.CATEGORIES]
            self.data_length = 0
            self.finished = False
            result = database.commit_query(
                "INSERT INTO profiler(username, category, length, timestamp, finished) VALUES (%s, %s, %s, %s, %s);",
                (username, ' '.join(map(str, self.category)), self.data_length,
                 datetime.utcnow().strftime("%d.%m.%YT%H:%M:%S"), False),
                con=mysql_con,
                close_con=False)
            if result <= 0:
                # Error
                print("[WARNING] Can't add Profiler for " + username)
            else:
                # Start analyze Thread, if the profiler existed bevor, this thread already run!
                self.analyze_thread = Thread(target=self.analyze_activity)
                self.analyze_thread.name = "Analyze Activities from " + username
                self.analyze_thread.daemon = True
                self.analyze_thread.start()
        else:
            # Load existent Profiler
            self.update_timestamp()

            self.category = [float(x) for x in result[0][1].split(' ')]
            self.data_length = result[0][2]
            self.finished = "1" in result[0][4]

        mysql_con.close()
        # Start finder thread
        self.find_posts_thread = Thread(target=self.find_interestings)
        self.find_posts_thread.name = "Find interesting Posts for " + username
        self.find_posts_thread.daemon = True
        if start_get_post_thread:
            self.find_posts_thread.start()
Example #29
0
def get_friends_data(username, follow_type):
    # Setup node list
    nodelist = NodeList()
    nodelist.update_nodes()
    nodes = nodelist.get_hive_nodes()
    hive = Hive(node=nodes)
    hive.set_default_nodes(nodes)
    # logging.warning(hive.config.items())

    # Create account object
    try:
        account = Account(username)
        logging.warning(account)
    except Exception as e:
        logging.warning(e)
        return {}

    followers = account.get_followers()
    following = account.get_following()

    if follow_type == 'followers':
        return make_dict(followers, following)
    else:
        return make_dict(following, followers)
Example #30
0
def list_proposals_by_node(creator, private_key, nodes, subjects):
    for idx in range(0, len(nodes)):
        node = nodes[idx]
        logger.info("Listing proposals using node at {}".format(node))
        s = Hive(node=[node], keys=[private_key])
        proposals = s.rpc.list_proposals([creator], 1000, "by_creator",
                                         "ascending", "all")
        for subject in subjects:
            msg = "Looking for id of proposal with subject {}".format(subject)
            for proposal in proposals:
                if proposal['subject'] == subject:
                    msg = msg + " - FOUND ID = {}".format(proposal['id'])
                    #assert proposal['id'] == results[subject], "ID do not match expected {} got {}".format(results[subject], proposal['id'])
                    break
            logger.info(msg)