示例#1
0
def profiling(name_list):
    hv = Hive()
    set_shared_hive_instance(hv)
    del hv
    print("start")
    for name in name_list:
        print("account: %s" % (name))
        acc = Account(name)
        max_index = acc.virtual_op_count()
        print(max_index)
        stopTime = datetime(2018, 4, 22, 0, 0, 0)
        hist_elem = None
        for h in acc.history_reverse(stop=stopTime):
            hist_elem = h
        print(hist_elem)
    print("blockchain")
    blockchain_object = Blockchain()
    current_num = blockchain_object.get_current_block_num()
    startBlockNumber = current_num - 20
    endBlockNumber = current_num
    block_elem = None
    for o in blockchain_object.stream(start=startBlockNumber,
                                      stop=endBlockNumber):
        print("block %d" % (o["block_num"]))
        block_elem = o
    print(block_elem)
示例#2
0
 def test_estimate_virtual_op_num(self):
     hv = self.bts
     account = Account("gtg", hive_instance=hv)
     block_num = 21248120
     block = Block(block_num, hive_instance=hv)
     op_num1 = account.estimate_virtual_op_num(block.time(),
                                               stop_diff=1,
                                               max_count=100)
     op_num2 = account.estimate_virtual_op_num(block_num,
                                               stop_diff=1,
                                               max_count=100)
     op_num3 = account.estimate_virtual_op_num(block_num,
                                               stop_diff=100,
                                               max_count=100)
     op_num4 = account.estimate_virtual_op_num(block_num,
                                               stop_diff=0.00001,
                                               max_count=100)
     self.assertTrue(abs(op_num1 - op_num2) < 2)
     self.assertTrue(abs(op_num1 - op_num4) < 2)
     self.assertTrue(abs(op_num1 - op_num3) < 200)
     block_diff1 = 0
     block_diff2 = 0
     for h in account.get_account_history(op_num4 - 1, 0):
         block_diff1 = (block_num - h["block"])
     for h in account.get_account_history(op_num4 + 1, 0):
         block_diff2 = (block_num - h["block"])
     self.assertTrue(block_diff1 > 0)
     self.assertTrue(block_diff2 <= 0)
示例#3
0
    def setUpClass(cls):
        nodelist = NodeList()
        nodelist.update_nodes(hive_instance=Hive(
            node=nodelist.get_nodes(exclude_limited=False), num_retries=10))
        cls.bts = Hive(node=nodelist.get_nodes(exclude_limited=True),
                       nobroadcast=True,
                       keys={"active": wif},
                       num_retries=10)
        # from getpass import getpass
        # self.bts.wallet.unlock(getpass())
        set_shared_hive_instance(cls.bts)
        cls.bts.set_default_account("test")

        acc = Account("bhive.app", hive_instance=cls.bts)
        n_votes = 0
        index = 0
        while n_votes == 0:
            comment = acc.get_feed(limit=30)[::-1][index]
            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)
示例#4
0
    def verify(self, **kwargs):
        """ Verify a message with an account's memo key

            :param str account: (optional) the account that owns the bet
                (defaults to ``default_account``)

            :returns: True if the message is verified successfully

            :raises InvalidMessageSignature: if the signature is not ok

        """
        # Split message into its parts
        parts = re.split("|".join(MESSAGE_SPLIT), self.message)
        parts = [x for x in parts if x.strip()]

        if not len(parts) > 2:
            raise AssertionError("Incorrect number of message parts")

        message = parts[0].strip()
        signature = parts[2].strip()
        # Parse the meta data
        meta = dict(re.findall(r'(\S+)=(.*)', parts[1]))

        # Ensure we have all the data in meta
        if "account" not in meta:
            raise AssertionError()
        if "memokey" not in meta:
            raise AssertionError()
        if "block" not in meta:
            raise AssertionError()
        if "timestamp" not in meta:
            raise AssertionError()

        # Load account from blockchain
        account = Account(
            meta.get("account"),
            hive_instance=self.hive)

        # Test if memo key is the same as on the blockchain
        if not account["memo_key"] == meta["memokey"]:
            log.error(
                "Memo Key of account {} on the Blockchain".format(
                    account["name"]) +
                "differs from memo key in the message: {} != {}".format(
                    account["memo_key"], meta["memokey"]
                )
            )

        # Reformat message
        message = SIGNED_MESSAGE_META.format(**locals())

        # Verify Signature
        pubkey = verify_message(message, unhexlify(signature))

        # Verify pubky
        pk = PublicKey(hexlify(pubkey).decode("ascii"))
        if format(pk, self.hive.prefix) != meta["memokey"]:
            raise InvalidMessageSignature

        return True
示例#5
0
    def setUpClass(cls):
        nodelist = NodeList()
        nodelist.update_nodes(hive_instance=Hive(
            node=nodelist.get_nodes(exclude_limited=False), num_retries=10))
        node_list = nodelist.get_nodes(exclude_limited=True)

        cls.bts = Hive(node=node_list,
                       use_condenser=True,
                       nobroadcast=True,
                       unsigned=True,
                       keys={"active": wif},
                       num_retries=10)
        cls.hiveio = Hive(node="https://api.hive.blog",
                          nobroadcast=True,
                          unsigned=True,
                          keys={"active": wif},
                          num_retries=10)
        acc = Account("bhive.app", hive_instance=cls.bts)
        comment = acc.get_feed(limit=20)[-1]
        cls.authorperm = comment.authorperm
        [author, permlink] = resolve_authorperm(cls.authorperm)
        cls.author = author
        cls.permlink = permlink
        cls.category = comment.category
        cls.title = comment.title
示例#6
0
文件: views.py 项目: holgern/hiveview
def blog_posts(request, author):
    author = re.sub(r'(\/)', '', author)
    account = Account(author, hive_instance=hv)
    posts = account.get_blog()
    for post in posts:
        if post:
            post = strip(post)
    return render(request, 'blog/post_list.html', {'posts': posts})
示例#7
0
文件: views.py 项目: holgern/hiveview
def request_author(request, *args, **kwargs):
    if(request.GET.get('req_author')):
        author = str(request.GET.get('author'))
    else:
        if 'author' in kwargs:
            author = kwargs['author']
    account = Account(author)
    return render(request, 'blog/account.html', {'account': account})
示例#8
0
 def test_follow_posting_key(self):
     nodelist = NodeList()
     hv = Hive(node=self.nodes,
                 keys=[self.posting_key],
                 nobroadcast=True,
                 expiration=120,
                 num_retries=10)
     account = Account("bhive", hive_instance=hv)
     account.follow("bhive1")
示例#9
0
 def test_account(self, node_param):
     if node_param == "instance":
         set_shared_hive_instance(self.bts)
         acc = Account("test")
         self.assertIn(acc.hive.rpc.url, self.urls)
         self.assertIn(acc["balance"].hive.rpc.url, self.urls)
         with self.assertRaises(RPCConnection):
             Account("test",
                     hive_instance=Hive(node="https://abc.d",
                                        autoconnect=False,
                                        num_retries=1))
     else:
         set_shared_hive_instance(
             Hive(node="https://abc.d", autoconnect=False, num_retries=1))
         hv = self.bts
         acc = Account("test", hive_instance=hv)
         self.assertIn(acc.hive.rpc.url, self.urls)
         self.assertIn(acc["balance"].hive.rpc.url, self.urls)
         with self.assertRaises(RPCConnection):
             Account("test")
示例#10
0
 def setUpClass(cls):
     cls.nodelist = NodeList()
     cls.nodelist.update_nodes(hive_instance=Hive(node=cls.nodelist.get_nodes(exclude_limited=False), num_retries=10))
     cls.bts = Hive(
         node=cls.nodelist.get_nodes(exclude_limited=True),
         nobroadcast=True,
         unsigned=True,
         data_refresh_time_seconds=900,
         keys={"active": wif, "owner": wif, "memo": wif},
         num_retries=10)
     cls.account = Account("test", full=True, hive_instance=cls.bts)
示例#11
0
 def test_blog_history(self):
     account = Account("bhive.app", hive_instance=self.bts)
     posts = []
     for p in account.blog_history(limit=5):
         if p["author"] != account["name"]:
             continue
         posts.append(p)
     self.assertTrue(len(posts) >= 1)
     self.assertEqual(posts[0]["author"], account["name"])
     self.assertTrue(posts[0].is_main_post())
     self.assertTrue(posts[0].depth == 0)
示例#12
0
 def test_approvewitness(self):
     bts = self.bts
     w = Account("bhive", hive_instance=bts)
     tx = w.approvewitness("bhive1")
     self.assertEqual(
         (tx["operations"][0][0]),
         "account_witness_vote"
     )
     op = tx["operations"][0][1]
     self.assertIn(
         "bhive1",
         op["witness"])
示例#13
0
    def test_default_connection(self):
        nodelist = NodeList()
        nodelist.update_nodes(hive_instance=Hive(
            node=nodelist.get_nodes(exclude_limited=False), num_retries=10))

        b2 = Hive(
            node=nodelist.get_nodes(exclude_limited=True),
            nobroadcast=True,
        )
        set_shared_hive_instance(b2)
        bts = Account("bhive")
        self.assertEqual(bts.hive.prefix, "STM")
示例#14
0
 def test_history_votes(self):
     hv = self.bts
     account = Account("gtg", hive_instance=hv)
     utc = pytz.timezone('UTC')
     limit_time = utc.localize(datetime.utcnow()) - timedelta(days=2)
     votes_list = []
     for v in account.history(start=limit_time, only_ops=["vote"]):
         votes_list.append(v)
     start_num = votes_list[0]["block"]
     votes_list2 = []
     for v in account.history(start=start_num, only_ops=["vote"]):
         votes_list2.append(v)
     self.assertTrue(abs(len(votes_list) - len(votes_list2)) < 2)
示例#15
0
 def test_verifyAuthority(self):
     hv = self.bts
     hv.wallet.unlock("123")
     tx = TransactionBuilder(use_condenser_api=True, hive_instance=hv)
     tx.appendOps(Transfer(**{"from": "bhive",
                              "to": "bhive1",
                              "amount": Amount("1.300 HBD", hive_instance=hv),
                              "memo": "Foobar"}))
     account = Account("bhive", hive_instance=hv)
     tx.appendSigner(account, "active")
     self.assertTrue(len(tx.wifs) > 0)
     tx.sign()
     tx.verify_authority()
     self.assertTrue(len(tx["signatures"]) > 0)
示例#16
0
 def test_update_memo_key(self):
     bts = self.bts
     bts.wallet.unlock("123")
     self.assertEqual(bts.prefix, "STX")
     acc = Account("bhive", hive_instance=bts)
     tx = acc.update_memo_key("STX55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n")
     self.assertEqual(
         (tx["operations"][0][0]),
         "account_update"
     )
     op = tx["operations"][0][1]
     self.assertEqual(
         op["memo_key"],
         "STX55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n")
示例#17
0
    def test_finalizeOps(self):
        bts = self.bts
        tx1 = bts.new_tx()
        tx2 = bts.new_tx()

        acc = Account("bhive", hive_instance=bts)
        acc.transfer("bhive1", 1, "HIVE", append_to=tx1)
        acc.transfer("bhive1", 2, "HIVE", append_to=tx2)
        acc.transfer("bhive1", 3, "HIVE", append_to=tx1)
        tx1 = tx1.json()
        tx2 = tx2.json()
        ops1 = tx1["operations"]
        ops2 = tx2["operations"]
        self.assertEqual(len(ops1), 2)
        self.assertEqual(len(ops2), 1)
示例#18
0
    def setUpClass(cls):
        nodelist = NodeList()
        nodelist.update_nodes(hive_instance=Hive(
            node=nodelist.get_nodes(exclude_limited=False), num_retries=10))
        node_list = nodelist.get_nodes(exclude_limited=True)

        cls.bts = Hive(
            node=node_list,
            nobroadcast=True,
            bundle=False,
            unsigned=True,
            # Overwrite wallet to use this list of wifs only
            keys={"active": wif},
            num_retries=10)
        cls.account = Account("bhive.app", hive_instance=cls.bts)
        set_shared_hive_instance(cls.bts)
示例#19
0
    def test_history_reverse2(self):
        hv = self.bts
        account = Account("bhive.app", hive_instance=hv)
        h_list = []
        max_index = account.virtual_op_count()
        for h in account.history_reverse(start=max_index,
                                         stop=max_index - 4,
                                         use_block_num=False,
                                         batch_size=2,
                                         raw_output=False):
            h_list.append(h)
        self.assertEqual(len(h_list), 5)
        for i in range(1, 5):
            self.assertEqual(h_list[i]["index"] - h_list[i - 1]["index"], -1)

        h_list = []
        for h in account.history_reverse(start=max_index,
                                         stop=max_index - 4,
                                         use_block_num=False,
                                         batch_size=6,
                                         raw_output=False):
            h_list.append(h)
        self.assertEqual(len(h_list), 5)
        for i in range(1, 5):
            self.assertEqual(h_list[i]["index"] - h_list[i - 1]["index"], -1)

        h_list = []
        for h in account.history_reverse(start=max_index,
                                         stop=max_index - 4,
                                         use_block_num=False,
                                         batch_size=6,
                                         raw_output=True):
            h_list.append(h)
        self.assertEqual(len(h_list), 5)
        for i in range(1, 5):
            self.assertEqual(h_list[i][0] - h_list[i - 1][0], -1)

        h_list = []
        for h in account.history_reverse(start=max_index,
                                         stop=max_index - 4,
                                         use_block_num=False,
                                         batch_size=2,
                                         raw_output=True):
            h_list.append(h)
        self.assertEqual(len(h_list), 5)
        for i in range(1, 5):
            self.assertEqual(h_list[i][0] - h_list[i - 1][0], -1)
示例#20
0
    def test_sign_message(self):
        def new_refresh(self):
            dict.__init__(
                self, {
                "identifier": "test",
                "name": "test",
                "id_item": "name",
                "memo_key": "STM6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV"
                })

        with mock.patch(
            "bhive.account.Account.refresh",
            new=new_refresh
        ):
            account = Account("test")
            account["memo_key"] = "STM6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV"
            p = Message("message foobar").sign(account=account)
            Message(p).verify(account=account)
示例#21
0
 def test_TransactionConstructor(self):
     hv = self.bts
     opTransfer = Transfer(**{"from": "bhive",
                              "to": "bhive1",
                              "amount": Amount("1 HIVE", hive_instance=hv),
                              "memo": ""})
     tx1 = TransactionBuilder(use_condenser_api=True, hive_instance=hv)
     tx1.appendOps(opTransfer)
     tx = TransactionBuilder(tx1, hive_instance=hv)
     self.assertFalse(tx.is_empty())
     self.assertTrue(len(tx.list_operations()) == 1)
     self.assertTrue(repr(tx) is not None)
     self.assertTrue(str(tx) is not None)
     account = Account("bhive", hive_instance=hv)
     tx.appendSigner(account, "active")
     self.assertTrue(len(tx.wifs) > 0)
     tx.sign()
     self.assertTrue(len(tx["signatures"]) > 0)
示例#22
0
 def test_account_by_pub(self):
     hv = self.hv
     self.wallet.hive = hv
     self.wallet.unlock(pwd="TestingOneTwoThree")
     acc = Account("gtg")
     pub = acc["owner"]["key_auths"][0][0]
     acc_by_pub = self.wallet.getAccount(pub)
     self.assertEqual("gtg", acc_by_pub["name"])
     gen = self.wallet.getAccountsFromPublicKey(pub)
     acc_by_pub_list = []
     for a in gen:
         acc_by_pub_list.append(a)
     self.assertEqual("gtg", acc_by_pub_list[0])
     gen = self.wallet.getAllAccounts(pub)
     acc_by_pub_list = []
     for a in gen:
         acc_by_pub_list.append(a)
     self.assertEqual("gtg", acc_by_pub_list[0]["name"])
     self.assertEqual(pub, acc_by_pub_list[0]["pubkey"])
示例#23
0
def profiling(node, name_list, shared_instance=True, clear_acc_cache=False, clear_all_cache=True):
    print("shared_instance %d clear_acc_cache %d clear_all_cache %d" %
          (shared_instance, clear_acc_cache, clear_all_cache))
    if not shared_instance:
        hv = Hive(node=node)
        print(str(hv))
    else:
        hv = None
    acc_dict = {}
    for name in name_list:
        acc = Account(name, hive_instance=hv)
        acc_dict[name] = acc
        if clear_acc_cache:
            acc.clear_cache()
        acc_dict = {}
    if clear_all_cache:
        clear_cache()
    if not shared_instance:
        del hv.rpc
示例#24
0
    def setUpClass(cls):
        cls.nodelist = NodeList()
        cls.nodelist.update_nodes(hive_instance=Hive(
            node=cls.nodelist.get_nodes(
                exclude_limited=False), num_retries=10))
        hv = Hive(node=cls.nodelist.get_nodes())
        hv.config.refreshBackup()
        hv.set_default_nodes(["xyz"])
        del hv

        cls.urls = cls.nodelist.get_nodes(exclude_limited=True)
        cls.bts = Hive(node=cls.urls, nobroadcast=True, num_retries=10)
        set_shared_hive_instance(cls.bts)
        acc = Account("bhive.app", hive_instance=cls.bts)
        comment = acc.get_blog(limit=20)[-1]
        cls.authorperm = comment.authorperm
        votes = acc.get_account_votes()
        last_vote = votes[-1]
        cls.authorpermvoter = '@' + last_vote['authorperm'] + '|' + acc["name"]
示例#25
0
    def upload(self, image, account, image_name=None):
        """ Uploads an image

            :param image: path to the image or image in bytes representation which should be uploaded
            :type image: str, bytes
            :param str account: Account which is used to upload. A posting key must be provided.
            :param str image_name: optional

            .. code-block:: python

                from bhive import Hive
                from bhive.imageuploader import ImageUploader
                hv = Hive(keys=["5xxx"]) # private posting key
                iu = ImageUploader(hive_instance=hv)
                iu.upload("path/to/image.png", "account_name") # "private posting key belongs to account_name

        """
        account = Account(account, hive_instance=self.hive)
        if "posting" not in account:
            account.refresh()
        if "posting" not in account:
            raise AssertionError("Could not access posting permission")
        for authority in account["posting"]["key_auths"]:
            posting_wif = self.hive.wallet.getPrivateKeyForPublicKey(
                authority[0])

        if isinstance(image, string_types):
            image_data = open(image, 'rb').read()
        elif isinstance(image, io.BytesIO):
            image_data = image.read()
        else:
            image_data = image

        message = py23_bytes(self.challenge, "ascii") + image_data
        signature = sign_message(message, posting_wif)
        signature_in_hex = hexlify(signature).decode("ascii")

        files = {image_name or 'image': image_data}
        url = "%s/%s/%s" % (self.base_url, account["name"], signature_in_hex)
        r = requests.post(url, files=files)
        return r.json()
示例#26
0
    def sign(self, account=None, **kwargs):
        """ Sign a message with an account's memo key

            :param str account: (optional) the account that owns the bet
                (defaults to ``default_account``)

            :returns: the signed message encapsulated in a known format

        """
        if not account:
            if "default_account" in config:
                account = config["default_account"]
        if not account:
            raise ValueError("You need to provide an account")

        # Data for message
        account = Account(account, hive_instance=self.hive)
        info = self.hive.info()
        meta = dict(
            timestamp=info["time"],
            block=info["head_block_number"],
            memokey=account["memo_key"],
            account=account["name"])

        # wif key
        wif = self.hive.wallet.getPrivateKeyForPublicKey(
            account["memo_key"]
        )

        # signature
        message = self.message.strip()
        signature = hexlify(sign_message(
            SIGNED_MESSAGE_META.format(**locals()),
            wif
        )).decode("ascii")

        message = self.message
        return SIGNED_MESSAGE_ENCAPSULATED.format(
            MESSAGE_SPLIT=MESSAGE_SPLIT,
            **locals()
        )
示例#27
0
 def test_appendSigner(self):
     nodelist = NodeList()
     hv = Hive(node=self.nodes,
                 keys=[self.active_key],
                 nobroadcast=True,
                 expiration=120,
                 num_retries=10)
     tx = TransactionBuilder(use_condenser_api=True, hive_instance=hv)
     tx.appendOps(Transfer(**{"from": "bhive",
                              "to": "bhive1",
                              "amount": Amount("1 HIVE", hive_instance=hv),
                              "memo": ""}))
     account = Account("bhive", hive_instance=hv)
     with self.assertRaises(
         AssertionError
     ):
         tx.appendSigner(account, "abcdefg")
     tx.appendSigner(account, "active")
     self.assertTrue(len(tx.wifs) > 0)
     tx.sign()
     self.assertTrue(len(tx["signatures"]) > 0)
示例#28
0
 def test_transfer(self):
     bts = self.bts
     bts.nobroadcast = False
     bts.wallet.unlock("123")
     # bts.wallet.addPrivateKey(self.active_key)
     # bts.prefix ="STX"
     acc = Account("bhive", hive_instance=bts)
     tx = acc.transfer(
         "bhive1", 1.33, "HBD", memo="Foobar")
     self.assertEqual(
         tx["operations"][0][0],
         "transfer"
     )
     self.assertEqual(len(tx['signatures']), 1)
     op = tx["operations"][0][1]
     self.assertIn("memo", op)
     self.assertEqual(op["from"], "bhive")
     self.assertEqual(op["to"], "bhive1")
     amount = Amount(op["amount"], hive_instance=bts)
     self.assertEqual(float(amount), 1.33)
     bts.nobroadcast = True
示例#29
0
 def test_disallow(self):
     bts = self.bts
     acc = Account("bhive", hive_instance=bts)
     if sys.version > '3':
         _assertRaisesRegex = self.assertRaisesRegex
     else:
         _assertRaisesRegex = self.assertRaisesRegexp
     with _assertRaisesRegex(ValueError, ".*Changes nothing.*"):
         acc.disallow(
             "STX55VCzsb47NZwWe5F3qyQKedX9iHBHMVVFSc96PDvV7wuj7W86n",
             weight=1,
             threshold=1,
             permission="active"
         )
     with _assertRaisesRegex(ValueError, ".*Changes nothing!.*"):
         acc.disallow(
             "STX6MRyAjQq8ud7hVNYcfnVPJqcVpscN5So8BhtHuGYqET5GDW5CV",
             weight=1,
             threshold=1,
             permission="active"
         )
示例#30
0
        def lookup_accounts(acclist):
            def user_info(accounts):
                if len(acclist) != len(accounts):
                    print("OOPS:", len(acclist), len(accounts), acclist)
                for index in range(0, len(accounts)):
                    a = accounts[index]
                    account = acclist[index]
                    vp = (a["vesting_shares"].amount +
                          a["received_vesting_shares"].amount -
                          a["delegated_vesting_shares"].amount) / 1000000.0
                    fish = "redfish"
                    if vp >= 1.0:
                        fish = "minnow"
                    if vp >= 10.0:
                        fish = "dolphin"
                    if vp >= 100:
                        fish = "orca"
                    if vp > 1000:
                        fish = "whale"
                    racc = None
                    proxy = None
                    related = list()
                    if a["recovery_account"] != "hive" and a[
                            "recovery_account"] != "":
                        related.append(a["recovery_account"])
                    if a["proxy"] != "":
                        related.append(a["proxy"])
                    self.wtw.set_account_info(account, fish, related)
                    accl2 = list()
                    if racc is not None and racc not in self.looked_up:
                        accl2.append(racc)
                    if proxy is not None and proxy not in self.looked_up:
                        accl2.append(proxy)
                    if len(accl2) > 0:
                        lookup_accounts(accl2)

            accounts = []
            for a in acclist:
                accounts.append(Account(a))
            user_info(accounts)