def test_list_proposals(node, account, wif, subject): logger.info("Testing: list_proposals") s = Steem(nodes = [node], no_broadcast = False, keys = [wif]) # list inactive proposals, our proposal shoud be here proposals = s.list_proposals(account, "by_creator", "direction_ascending", 1000, "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.list_proposals(account, "by_creator", "direction_ascending", 1000, "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.list_proposals(account, "by_creator", "direction_ascending", 1000, "all") found = None for proposal in proposals: if proposal["subject"] == subject: found = proposal assert found is not None
def test_remove_proposal(node, account, wif, subject): logger.info("Testing: remove_proposal") s = Steem(nodes = [node], no_broadcast = False, keys = [wif]) # first we will find our special proposal and get its id proposals = s.list_proposals(account, "by_creator", "direction_ascending", 1000, "inactive") found = None for proposal in proposals: if proposal["subject"] == subject: found = proposal assert found is not None proposal_id = int(found["id"]) # remove proposal s.commit.remove_proposal(account, [proposal_id]) # try to find our special proposal proposals = s.list_proposals(account, "by_creator", "direction_ascending", 1000, "inactive") found = None for proposal in proposals: if proposal["subject"] == subject: found = proposal assert found is None
def test_list_voter_proposals(node, account, wif, subject): logger.info("Testing: list_voter_proposals") s = Steem(nodes = [node], no_broadcast = False, keys = [wif]) voter_proposals = s.list_voter_proposals(account, "by_creator", "direction_ascending", 1000, "inactive") found = None for voter, proposals in voter_proposals.items(): for proposal in proposals: if proposal["subject"] == subject: found = proposal assert found is not None
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 = Steem(nodes = [node], keys = [private_key]) proposals = s.list_proposals(creator, "by_creator", "direction_ascending", 1000, "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)
class CustomClient(commands.Bot): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.config = kwargs.get("config") self.steem = Steem(nodes=["https://api.steemit.com"]) self.db = Database() @asyncio.coroutine def on_ready(self): for server in self.servers: print(f'Running on {server.name}') def say_error(self, error): return self.say(f":exclamation: {error}") def say_success(self, message): return self.say(f":thumbsup: {message}") def steem_username_is_valid(self, username): resp = self.steem.get_accounts([username]) return bool(len(resp)) @property def running_on(self): return list(self.servers)[0]
def run_worker(worker_name): mongo = MongoStorage(db_name=os.getenv('DB_NAME', DB_NAME), host=os.getenv('DB_HOST', MONGO_HOST), port=os.getenv('DB_PORT', MONGO_PORT)) stm = Steem() while True: try: if worker_name == "scrape_operations": mongo.ensure_indexes() scrape_operations(mongo, stm) elif worker_name == "validate_operations": validate_operations(mongo, stm) elif worker_name == "scrape_all_users": scrape_all_users(mongo, stm) elif worker_name == "scrape_active_posts": scrape_active_posts(mongo, stm) elif worker_name == "scrape_prices": scrape_prices(mongo) elif worker_name == "refresh_dbstats": refresh_dbstats(mongo) elif worker_name == "override": override(mongo) except (KeyboardInterrupt, SystemExit): exit("Quitting...") except: print("EXCEPTION: %s():" % worker_name) print(traceback.format_exc()) # prevent IO overflow time.sleep(5)
def verify_key(self, name, key): s = Steem(keys=key) try: pubkey = PrivateKey(key).pubkey account = s.get_account(name) pubkey2 = account['posting']['key_auths'][0][0] if str(pubkey) != str(pubkey2): return False return True except Exception as e: print(9) print(e) return False
def vote(author, permlink, kind): if 'logged_in' in session and session[ 'logged_in'] and 'authorized' in session and session[ 'authorized'] and 'username' in session: try: weight = 100 if kind == "flag": weight = -100 identifier = "@" + author + "/" + permlink if 'POST_TO_STEEM' in app.config and app.config[ 'POST_TO_STEEM'] == "1": s = Steem( nodes=[ 'https://rpc.buildteam.io', 'https://api.steemit.com', 'https://steemd.steemitstage.com' ], keys=[app.config['POSTING_KEY'], app.config['ACTIVE_KEY']]) p = s.commit.vote(identifier, weight, account=session['username']) app.logger.info(p) return jsonify({'status': True}) except Exception as e: app.logger.info(e) return jsonify({'status': False, 'msg': 'unknown exception'}) else: return jsonify({ 'status': False, 'msg': 'please login and authorize first' })
def main(): parser = argparse.ArgumentParser() parser.add_argument("config", help="Config file in JSON format") parser.add_argument("--post-daily-flag-report", help="Posts daily flag report") args = parser.parse_args() config = json.loads(open(args.config).read()) keys = [config.get("posting_key")] if config.get("flag_options") and \ 'from_account_posting_key' in config.get("flag_options"): keys.append(config["flag_options"]["from_account_posting_key"]) steemd_instance = Steem( nodes=config["nodes"], keys=keys, ) sherlock = Sherlock( steemd_instance, config, ) if args.post_daily_flag_report: sherlock.post_daily_flag_report() return sherlock.run()
def submit_post(title, tags, body, author): steemPostingKey = os.environ.get('steemPostingKey') steem = Steem(wif=steemPostingKey) permlink_title = ''.join(e for e in title if e.isalnum()).lower() permlink = "{}-%s%s".format(permlink_title) % ( time.strftime("%Y%m%d%H%M%S"), random.randrange(0, 9999, 1)) try: steem.post(title, body, author, permlink, None, None, None, None, tags, None, True) print("Submitted post") except Exception as error: print(repr(error)) return permlink
def make_vote(self, ratio, post_link,account_name): account_info_post = interpret.get_account_info(account_name,self.main.active_key, self.main.sending_account, self.main.memo_account, self.main.nodes[0]) if account_info_post: account_info_post = account_info_post[2] # takes ratio and post link and calculates the vote on the post, and returns it for use in the post memo if ratio < self.vote_threshold: return 0 if account_info_post: upvote_tokens = account_info_post["token-upvote-perm"] #+ self.account_info[post_link]["token-upvote-temp"] else: upvote_tokens = 0 equation = self.average_post[0] * (math.sqrt(upvote_tokens)/25 + 1) * (ratio/self.average_post[1]) if equation > 100: equation = 100 elif equation < 0.1: return 0 for i in self.nodes: try: steem = Steem(node=i, keys=self.posting_key) steem.vote("@"+post_link.split("@")[1], equation, account=self.sending_account) return equation except Exception as e: print(e) pass return 0
class Steemfunc: def __init__(self): Nodes = [ 'https://gtg.steem.house:8090', 'https://seed.bitcoiner.me', 'https://steemd.minnowsupportproject.org', 'https://steemd.privex.io', 'https://steemd.steemit.com', 'https://rpc.steemliberator.com', 'https://steemd.minnowsupportproject.org' ] Nodes_1 = ['https://api.steemit.com'] # self.steemNode = Steem(Nodes) self.steemNode = Steem(Nodes_1) self.num_posts = 1 self.sort = 'created' self.tag = 'kr-event' def get_latest_user_post(self, _user='******', _limit=1): posts = self.steemNode.get_blog(_user, 0, _limit) for post in posts: if _user == post['comment']['author']: #print(post['comment']['title']) return post def get_latest_user_post_link(self, _user='******', _limit=1): posts = self.steemNode.get_blog(_user, 0, _limit) for post in posts: if _user == post['comment']['author']: url = 'https://busy.org/' + post['comment'][ 'category'] + '/@' + post['comment'][ 'author'] + '/' + post['comment']['permlink'] return url def get_latest_posts(self, _sort='created', _tag='kr-event', _period=1): posts = self.steemNode.get_posts(self.num_posts, _sort, _tag) post = posts[0] return post def print_post_link(self, _post): url = 'https://busy.org/' + _post['tags'][0] + '/@' + _post[ 'author'] + '/' + _post['permlink'] print(url) def get_post_link(self, _post): url = 'https://busy.org/' + _post['tags'][0] + '/@' + _post[ 'author'] + '/' + _post['permlink'] return url
def scrape_blockchain(mongo): s = Steem() # see how far behind we are missing = list(range(last_block_num(mongo), s.last_irreversible_block_num)) # if we are far behind blockchain head # split work in chunks of 100 if len(missing) > 100: for batch in partition_all(100, missing): results = s.get_blocks(batch) insert_blocks(mongo, results) # otherwise continue as normal blockchain = Blockchain(mode="irreversible") hist = blockchain.stream_from(start_block=last_block_num(mongo), full_blocks=True) insert_blocks(mongo, hist)
def x_verify_key(acctname, private_posting_key, mode): # Verify a Steemit Private Posting Key pubkey = 0 acct = "" # Get a new instance of the Steemd node with the key to be tested try: steem = Steem(nodes, keys=[private_posting_key]) except InvalidWifError as e: if mode != "quiet": print("Invalid key: " + str(e)) return False # Convert the Private Posting Key into the Public Posting Key try: pubkey = PrivateKey(private_posting_key).pubkey except: if mode != "quiet": print("Bad private key") return False # Get the account for which the key is to be tested against try: acct = steem.get_account(acctname) except: if mode != "quiet": print("Could not connect to steemd") return False # Compare the Public Posting Keys with each other if acct: pubkey2 = acct['posting']['key_auths'][0][0] if str(pubkey) != str(pubkey2): if mode != "quiet": print("The private key and account name provided do not match.") return False else: if mode != "quiet": print("Private key is valid.") return True
def listen(config, daily_message): logger.info('Starting TX listener...') steem = Steem(nodes=config.get("nodes"), keys=config["keys"]) tx_listener = TransactionListener(steem, config) if daily_message == '1': tx_listener.daily_message() return tx_listener.run()
def index(request): try: s = Steem(nodes=["https://api.steemit.com"]) author, permlink = request.GET['p'].split("/") post = s.get_content(author, permlink) json_metadata = json.loads(post["json_metadata"]) tagstring = "" for tag in json_metadata["tags"]: if not tag == tagstring[:-1]: tagstring += tag + "," return HttpResponse(tagstring[:-1], content_type='text/plain') except: return HttpResponse( "To use this API call, please supply param p=account/post, substituting account/post with the account and permlink of the post.\n\n" 'Example: https://api.steem.place/getPostBody/?p=moisesmcardona/preparing-dinner-2-chicken-thights\n\n' 'Returns: Post Tags, separated by comma (,)', content_type='text/plain')
def __init__(self, community_name: str, account_name: str, steem_instance: Steem = None, **kwargs): self.steem = steem_instance or Steem(**kwargs) self.community = community_name self.account = account_name
def get_steem_conn(): global _steem_conn if _steem_conn is None: _steem_conn = Steem(nodes=NODES, keys=[ BOT_POSTING_KEY, ]) return _steem_conn
def reconfigure_node(self): self.node_index = (self.node_index + 1) % len(self.list) self.nodes = [self.list[self.node_index]] self.steem = Steem(wif=self.steemPostingKey, nodes=self.nodes) self.b = Blockchain(self.steem) self.queue.steem = self.steem print('New node: {}\n'.format(self.nodes))
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 = Steem(nodes = [self.node_url], keys = [self.private_key])
def run(): steem = Steem() blockchain = Blockchain() stream = blockchain.stream(filter_by=["transfer"]) username = "******" while True: try: for transfer in stream: if transfer["to"] == username: url, permlink = transfer["memo"].split("@") if "https://steemit.com/" in url: steem.vote(f"@{permlink}", 100) except Exception as error: print(repr(error)) continue
def get_steem_conn(nodes): global _steem_conn if _steem_conn is None: _steem_conn = Steem(nodes=nodes, # keys=[os.getenv("POSTING_KEY"), ] ) return _steem_conn
def __init__(self): self.steem = Steem() self.account = "funfund" overview = self.steem.get_reward_fund("post") steem_prices = self.steem.get_current_median_history_price() self.reward_balance = Decimal(overview['reward_balance'].replace( ' STEEM', '')) self.recent_claims = Decimal(overview['recent_claims']) self.feed_price = Decimal(steem_prices['base'].replace(' SBD', '')) print("Reward balance: {}".format(self.reward_balance)) print("Recent claims: {}".format(self.recent_claims)) print("Feed price: {}".format(self.feed_price)) self.connObj = DBActions()
def run(): account = "sttest1" account = Account(account) wif = os.environ.get("UNLOCK") steem = Steem(wif=wif) blockchain = Blockchain() stream = map(Post, blockchain.stream(filter_by=["comment"])) upvote_list = json.load(open('upvote_list.json')) upvoted = {} upvote_queue = {} date = int(time.strftime("%d")) hour = int(time.strftime("%-H")) print("Entering blockchain stream!") while True: try: for post in stream: time_string = str(post.time_elapsed()) post_age = time_string.split(":") try: # Omit posts older than 10 min if int(post_age[0]) > 0 or int(post_age[1]) > 10: break except Exception as e: #print (repr(e)) break # start upvoting cycle at 100% voting power if account.voting_power() == 100: start_upvote_cycle(upvote_queue, account, steem) # check for new date if int(time.strftime("%d")) is not date: upvoted = {} date = int(time.strftime("%d")) #check for new hour if int(time.strftime("%-H")) is not hour: upvote_list = json.load(open('upvote_list.json')) hour = int(time.strftime("%-H")) # verify post and add to queue if valid_post(post, upvote_list, upvoted): try: author = post["author"] print ("\nAdding to queue{}\nPermlink: {}".format(author, post['identifier'])) if post['identifier'] not in upvote_queue: upvote_queue[post['identifier']] = upvote_list[author]["upvote_weight"] print ("Upvoted {} for {}%".format(author, upvote_list[author]["upvote_weight"])) upvoted[author] += 1 except Exception as error: print(repr(error)) continue except Exception as error: #print(repr(error)) continue
class SteemitClient(): def __init__(self, account, private_key): self.account_name = account self.connection = Steem(keys=[private_key]) # TODO not working def send_post(self, author, title, body): assert False self.connection.commit.post(title, msg_body, self.account_name) def send_low_level_post(self, author, title, body, parent_link): # TODO reply not working try: self.connection.commit.post( title, body, self.account_name, reply_identifier=f'{self.account_name}/{parent_link}') except: print("No post to steem") def get_posts(self, permlink_collection): votes = [] msgs = [] for i in self.connection.get_content_replies(self.account_name, permlink_collection): if i['author'] == self.account_name: permlink = i['permlink'] parent_permlink = i['parent_permlink'] body_row = i['body'] if 'votee' in body_row: votes.append(body_row) else: msgs.append(body_row) for j in self.connection.get_content_replies( self.account_name, permlink): if j['author'] == self.account_name: permlink = j['permlink'] parent_permlink = j['parent_permlink'] body_row = j['body'] votes.append(body_row) return msgs, votes
def get_user_posts(username, from_id, limit=60): s = Steem(nodes=settings.STEEM_NODES) blog_entries = s.get_blog( account=username, entry_id=from_id, limit=limit, ) entries_list = [] for entry in blog_entries: comment = entry['comment'] # Could be util to load posts on utopian directly. # parent_permlink = comment.get('permlink') author = comment.get('author') if username == author: metadata = json.loads(comment.get('json_metadata')) category = comment.get('category') metadata = json.loads(comment.get('json_metadata')) entry_dict = { 'id': comment.get('id'), 'title': comment.get('title'), 'clickable': 'https://www.steemit.com/{0}/@{1}/{2}'.format( category, author, comment.get('permlink'), ), 'url': '/{0}/@{1}/{2}'.format( category, author, comment.get('permlink'), ), 'author': author, 'category': category, 'tags': metadata.get('tags'), 'images': metadata.get('image'), 'entry_id': entry['entry_id'] } entries_list.append(entry_dict) return entries_list
def index(request): try: s = Steem(nodes=["https://api.steemit.com"]) try: account = s.get_account(request.GET['a']) votes = account["witness_votes"] votelist = "" for vote in votes: votelist += vote + "," except: votelist = '' return HttpResponse(votelist, content_type='text/plain') except: return HttpResponse( "To use this API call, please supply param a=accountname, substituting accountname with the account to see its Witness Votes.\n\n" 'Example: https://api.steem.place/getWitnessVotes/?a=moisesmcardona\n\n' 'Returns: Witnesses voted by account, separated by comma (,)', content_type='text/plain')
def __init__(self, config): self.config = config self.blockchain = Blockchain() self.loop = asyncio.get_event_loop() self.ps = TransferStream(BlockPointer(), config) self.executor = ThreadPoolExecutor(max_workers=1) self.instance = None self.run = False self.steem = Steem()
def index(request): if request.method == 'POST': try: pk = [request.POST['pk']] steem = Steem(keys=pk[0], nodes=["https://api.steemit.com"]) steem.resteem(request.POST['i'], account=request.POST['a']) return HttpResponse('ok', content_type='text/plain') except: return HttpResponse( 'An error has occurred while resteeming the post', content_type='text/plain') else: return HttpResponse( 'This is a POST request. To resteem a post, send the following parameters:\n' 'pk = private key\n' 'i = post identifier\n' 'a = account', content_type='text/plain')
class SteemHandler(object): def __init__(self): if settings.STEEM_NODES: self.steem = Steem(nodes=settings.STEEM_NODES) else: self.steem = Steem() def get_account(self, name): return self.steem.get_account(name)
def __init__(self, block, block_count, operation): self.block = block self.end_block = block_count + self.block - 1 self.operation = operation self.nodes = ['https://rpc.buildteam.io', 'https://api.steemit.com', 'https://rpc.steemviz.com'] self.steem = Steem(nodes=self.nodes) self.b = Blockchain(self.steem) print('Booted\nConnected to: {}'.format(self.nodes[0]))
def __init__(self, config, db): self.config = config self.db = db keypath = os.path.expanduser(self.config['keyfile_path']) with open(keypath) as key_file: key_file_json = json.load(key_file) self.steem = Steem(keys=key_file_json['krguidedog']) self.message1 = readFile(self.config['guidedog']['mild_warning_file']) self.message2 = readFile( self.config['guidedog']['moderate_warning_file']) self.message3 = readFile(self.config['guidedog']['hard_warning_file']) self.copyright = readFile(self.config['guidedog']['copyright_file']) self.copyright_eng = readFile( self.config['guidedog']['copyright_file_eng']) self.last_daily_report = None self.daily_report_generator = Publisher(self.db) self.daily_report_timestamp = None
def __init__(self, cache_timeout=60, steem_instance=None): if not steem_instance: steem_instance = Steem() self.steem = steem_instance self._cache_timeout = cache_timeout self._cache_timer = time.time() self._btc_usd = None self._steem_btc = None self._sbd_btc = None
def test_vote_proposal(node, account, wif, subject): logger.info("Testing: vote_proposal") s = Steem(nodes = [node], no_broadcast = False, keys = [wif]) # first we will find our special proposal and get its id proposals = s.list_proposals(account, "by_creator", "direction_ascending", 1000, "inactive") found = None for proposal in proposals: if proposal["subject"] == subject: found = proposal assert found is not None proposal_id = int(found["id"]) # now lets vote ret = s.commit.update_proposal_votes(account, [proposal_id], True) assert ret["operations"][0][1]["voter"] == account assert ret["operations"][0][1]["proposal_ids"][0] == proposal_id assert ret["operations"][0][1]["approve"] == True steem_utils.steem_tools.wait_for_blocks_produced(2, node)
def inspect_steemd_implementation(): """ Compare implemented methods with current live deployment of steemd. """ _apis = distinct(pluck('api', api_methods)) _methods = set(pluck('method', api_methods)) avail_methods = [] s = Steem(re_raise=False) for api in _apis: err = s.exec('nonexistentmethodcall', api=api) [ avail_methods.append(x) for x in err['data']['stack'][0]['data']['api'].keys() ] avail_methods = set(avail_methods) print("\nMissing Methods:") pprint(avail_methods - _methods) print("\nLikely Deprecated Methods:") pprint(_methods - avail_methods)
account = {"name" : "tester001", "private_key" : "", "public_key" : ""} assert len(account["private_key"]) != 0, "Private key is empty" keys = [wif] keys.append(account["private_key"]) logger.info(keys) if node is not None: node.run_steem_node(["--enable-stale-production"]) try: if node is None or node.is_running(): node_client = Steem(nodes = [node_url], no_broadcast = False, keys = keys ) # create accounts create_accounts(node_client, args.creator, account) # tranfer to vesting transfer_to_vesting(node_client, args.creator, account, "300.000", "TESTS" ) # transfer assets to accounts transfer_assets_to_accounts(node_client, args.creator, account, "400.000", "TESTS" ) transfer_assets_to_accounts(node_client, args.creator, account, "400.000", "TBD"
from steem import Steem import random #create steem instance s = Steem() #set your username #my username as example user = '******' #set the link to your post #my previous post for example postLink = 'getting-started-with-steem-python-upvote-and-comment-bot-examples-linux' #get all the people who voted on the post voters = s.get_active_votes(user, postLink) #create a list of all the voters voterList = [user['voter'] for user in voters] #get a list of all the people who reblogged the post reblogs = s.get_reblogged_by(user, postLink) #get of your follower count followerCount = s.get_follow_count(user)['follower_count'] #retrieve all your followers names followers = s.get_followers(user, 0, 'blog', followerCount) #create a list of all your followers followerList = [follower['follower'] for follower in followers] #create a list of all the people who voted, reblogged and followed you potentialWinnerList = [] for potentialWinner in voterList: if potentialWinner in reblogs and potentialWinner in followerList: #user is following us and reblogged our post so lets add them to the list
import argparse parser = argparse.ArgumentParser() parser.add_argument("creator", help = "Account to create test accounts with") parser.add_argument("receiver", help = "Account to receive payment for proposal") parser.add_argument("wif", help="Private key for creator account") parser.add_argument("nodes_url", type=str, nargs="+", help="Url of working steem node") parser.add_argument("--delays", dest="delays", type=float, nargs="+", help="Delays for each worker/node (default 0)") parser.add_argument("--proposal-count", dest="proposal_count", type=int, default=1, help="Number of proposals each worker will create.") args = parser.parse_args() logger.info("Performing ID collision test with nodes {}".format(args.nodes_url)) import steem_utils.steem_tools node_client = Steem(nodes = args.nodes_url, keys = [args.wif]) logger.info("New post ==> ({},{},{},{},{})".format( "Steempy proposal title [{}]".format(args.creator), "Steempy proposal body [{}]".format(args.creator), args.creator, get_permlink(args.creator), "proposals" )) node_client.commit.post("Steempy proposal title [{}]".format(args.creator), "Steempy proposal body [{}]".format(args.creator), args.creator, permlink = get_permlink(args.creator), tags = "proposals" )
] if not accounts: logger.error("Accounts array is empty, please add accounts in a form {\"name\" : name, \"private_key\" : private_key, \"public_key\" : public_key}") sys.exit(1) keys = [wif] for account in accounts: keys.append(account["private_key"]) if node is not None: node.run_steem_node(["--enable-stale-production"]) try: if node is None or node.is_running(): node_client = Steem(nodes = [node_url], no_broadcast = False, keys = keys ) # create accounts test_utils.create_accounts(node_client, args.creator, accounts) # tranfer to vesting test_utils.transfer_to_vesting(node_client, args.creator, accounts, "300.000", "TESTS" ) # transfer assets to accounts test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, "400.000", "TESTS" ) test_utils.transfer_assets_to_accounts(node_client, args.creator, accounts, "400.000", "TBD"
def test_iterate_results_test(node, creator_account, receiver_account, wif, subject, remove): logger.info("Testing: test_iterate_results_test") # test for iterate prosals # 1 we will create n proposals of which k proposal will have the same value in one of the fields # 2 then we will list proposals starting from kth proposal with limit set to m < k # 3 we list proposals again with the same conditiona as in 2, we should get the same set of results # in real life scenatio pagination scheme with limit set to value lower than "k" will be showing # the same results and will hang # 4 then we will use newly introduced last_id field, we should see diferent set of proposals s = Steem(nodes = [node], no_broadcast = False, keys = [wif]) from steem.account import Account try: creator = Account(creator_account) except Exception as ex: logger.error("Account: {} not found. {}".format(creator_account, ex)) sys.exit(1) try: receiver = Account(receiver_account) except Exception as ex: logger.error("Account: {} not found. {}".format(receiver_account, ex)) sys.exit(1) import datetime now = datetime.datetime.now() # 1 we will create n proposals of which k proposal will have the same value in one of the fields # here we have 5 proposals with the same start date start_end_pairs = [ [1,1], [2,2], [4,3], [5,4], [5,5], [5,6], [5,7], [5,8], [6,9] ] for start_end_pair in start_end_pairs: start_date, end_date = test_utils.get_start_and_end_date(now, start_end_pair[0], start_end_pair[1]) s.commit.create_proposal( creator["name"], receiver["name"], start_date, end_date, "16.000 TBD", subject, "steempy-proposal-title" ) steem_utils.steem_tools.wait_for_blocks_produced(5, node) start_date = test_utils.date_to_iso(now + datetime.timedelta(days = 5)) # 2 then we will list proposals starting from kth proposal with limit set to m < k proposals = s.list_proposals(start_date, "by_start_date", "direction_descending", 3, "all") assert len(proposals) == 3, "Expected {} elements got {}".format(3, len(proposals)) ids = [] for proposal in proposals: assert proposal["start_date"] == start_date, "Expected start_date do not match {} != {}".format(start_date, proposals[-1]["start_date"]) ids.append(proposal["id"]) assert len(ids) == 3, "Expected {} elements got {}".format(3, len(ids)) # 3 we list proposals again with the same conditiona as in 2, we should get the same set of results proposals = s.list_proposals(start_date, "by_start_date", "direction_descending", 3, "all") assert len(proposals) == 3, "Expected {} elements got {}".format(3, len(proposals)) oids = [] for proposal in proposals: assert proposal["start_date"] == start_date, "Expected start_date do not match {} != {}".format(start_date, proposals[-1]["start_date"]) oids.append(proposal["id"]) assert len(oids) == 3, "Expected {} elements got {}".format(3, len(oids)) # the same set of results check for id in ids: assert id in oids, "Id not found in expected results array {}".format(id) # 4 then we will use newly introduced last_id field, we should see diferent set of proposals proposals = s.list_proposals(start_date, "by_start_date", "direction_descending", 3, "all", oids[-1]) start_date, end_date = test_utils.get_start_and_end_date(now, 5, 4) assert proposals[-1]["start_date"] == start_date, "Expected start_date do not match {} != {}".format(start_date, proposals[-1]["start_date"]) assert proposals[-1]["end_date"] == end_date, "Expected end_date do not match {} != {}".format(end_date, proposals[-1]["end_date"]) # remove all created proposals if remove: start_date = test_utils.date_to_iso(now + datetime.timedelta(days = 6)) for a in range(0, 2): proposals = s.list_proposals(start_date, "by_start_date", "direction_descending", 5, "all") ids = [] for proposal in proposals: ids.append(int(proposal['id'])) s.commit.remove_proposal(creator["name"], ids) steem_utils.steem_tools.wait_for_blocks_produced(3, node)