예제 #1
0
def benchmark_calls(node,
                    authorpermvoter,
                    num_retries=10,
                    num_retries_call=10,
                    timeout=60):
    block_count = 0
    history_count = 0
    access_time = timeout
    follow_time = 0
    sucessfull = False
    error_msg = None
    start_total = timer()
    account_name = "gtg"

    [author, permlink, voter] = resolve_authorpermvoter(authorpermvoter)
    authorperm = construct_authorperm(author, permlink)

    try:
        stm = Steem(node=node,
                    num_retries=num_retries,
                    num_retries_call=num_retries_call,
                    timeout=timeout)

        start = timer()
        Vote(authorpermvoter, steem_instance=stm)
        stop = timer()
        vote_time = stop - start
        start = timer()
        c = Comment(authorperm, steem_instance=stm)
        if c.title == '':
            raise AssertionError("title must not be empty!")
        stop = timer()
        comment_time = stop - start
        start = timer()
        acc = Account(author, steem_instance=stm)
        # if acc.json()["json_metadata"] == '':
        #    raise AssertionError("json_metadata must not be empty!")
        stop = timer()
        account_time = stop - start
        sucessfull = True
        access_time = (vote_time + comment_time + account_time) / 3.0
    except NumRetriesReached:
        error_msg = 'NumRetriesReached'
        sucessfull = False
    except KeyboardInterrupt:
        error_msg = 'KeyboardInterrupt'
        # quit = True
    except Exception as e:
        error_msg = str(e)
        sucessfull = False
    total_duration = float("{0:.2f}".format(timer() - start_total))
    access_time = float("{0:.3f}".format(access_time))
    return {
        'sucessfull': sucessfull,
        'node': node,
        'error': error_msg,
        'total_duration': total_duration,
        'access_time': access_time,
        'count': None
    }
예제 #2
0
 def rpc(self) -> Steem:
     if not self._rpc:
         # Use the symbol of the first coin for our settings.
         symbol = list(self.all_coins.keys())[0]
         _settings = self.all_coins[symbol].settings['json']
         rpcs = _settings.get('rpcs', settings.HIVE_RPC_NODES)
         
         # If you've specified custom RPC nodes in the custom JSON, make a new instance with those
         # Otherwise, use the global shared_steem_instance.
         rpc_conf = dict(num_retries=5, num_retries_call=3, timeout=20, node=rpcs)
         log.info('Getting BSteem instance for coin %s - settings: %s', symbol, rpc_conf)
         
         self._rpc = Steem(node=rpcs, **rpc_conf) if empty(rpcs, itr=True) else Steem(**rpc_conf)  # type: Steem
         self._rpc.set_password_storage(_settings.get('pass_store', 'environment'))
         self._rpcs[symbol] = self._rpc
     return self._rpc
예제 #3
0
def profiling(name_list):
    stm = Steem()
    set_shared_steem_instance(stm)
    del stm
    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.ops(start=startBlockNumber, stop=endBlockNumber):
        print("block %d" % (o["block_num"]))
        block_elem = o
    print(block_elem)
예제 #4
0
def transfer_to_someone(key, token, name, toplayer, money, memo):
    local_values.s = Steem(keys=[key])
    contract_payload = {
        'symbol': token,
        'to': toplayer,
        'quantity': str(money),
        'memo': memo
    }
    json_data = {
        'contractName': 'tokens',
        'contractAction': 'transfer',
        'contractPayload': contract_payload
    }
    kk = local_values.s.custom_json('ssc-mainnet1',
                                    json_data,
                                    required_auths=[name])

    tx = Signed_Transaction(kk)
    tx.data.pop("signatures", None)
    print(tx)
    h = hashlib.sha256(bytes(tx)).digest()
    transaction_id = hexlify(h[:20]).decode("ascii")
    print(transaction_id)
    url = "https://steemd.com/tx/%s" % transaction_id
    print(url)
    print("转账完成")
    return url
    def get_rpc(self, symbol: str) -> Steem:
        """
        Returns a Steem instance for querying data and sending TXs. By default, uses the Beem shared_steem_instance.

        If a custom RPC list is specified in the Coin "custom json" settings, a new instance will be returned with the
        RPCs specified in the json.

        :param symbol: Coin symbol to get Beem RPC instance for
        :return beem.steem.Steem: An instance of :class:`beem.steem.Steem` for querying
        """
        if symbol not in self._rpcs:
            settings = self.settings[symbol]['json']
            rpcs = settings.get('rpcs')
            rpc_conf = dict(num_retries=5,
                            num_retries_call=3,
                            timeout=20,
                            node=rpcs,
                            custom_chains=custom_chains)
            log.info('Getting Beem instance for coin %s - settings: %s',
                     symbol, rpc_conf)
            self._rpcs[symbol] = self.rpc if empty(rpcs, itr=True) else Steem(
                **rpc_conf)
            self._rpcs[symbol].set_password_storage(
                settings.get('pass_store', 'environment'))
        return self._rpcs[symbol]
예제 #6
0
def get_config_node(node,
                    num_retries=10,
                    num_retries_call=10,
                    timeout=60,
                    how_many_seconds=30):
    blockchain_version = u'0.0.0'
    is_hive = False
    sucessfull = True
    error_msg = None
    access_time = timeout
    config = {}
    start_total = timer()
    try:
        stm = Steem(node=node,
                    num_retries=num_retries,
                    num_retries_call=num_retries_call,
                    timeout=timeout)
        blockchain_version = stm.get_blockchain_version()
        is_hive = stm.is_hive
        start = timer()
        config = stm.get_config(use_stored_data=False)
        stop = timer()
        access_time = stop - start
        config_count = 0

    except NumRetriesReached:
        error_msg = 'NumRetriesReached'
        sucessfull = False
    except KeyboardInterrupt:
        error_msg = 'KeyboardInterrupt'
        # quit = True
    except Exception as e:
        error_msg = str(e)
    total_duration = float("{0:.2f}".format(timer() - start_total))
    access_time = float("{0:.2f}".format(access_time))
    ret = {
        'sucessfull': sucessfull,
        'node': node,
        'error': error_msg,
        'total_duration': total_duration,
        'count': None,
        'access_time': access_time,
        'version': blockchain_version,
        'config': config,
        'is_hive': is_hive
    }
    return ret
예제 #7
0
def daili(key, player, toplayer, sp):
    local_values.s = Steem(keys=[key])
    acc = Account(player, steem_instance=local_values.s)
    resp = acc.delegate_vesting_shares(toplayer,
                                       local_values.s.sp_to_vests(sp),
                                       account=player)

    print(resp)
 def setup(self):
     self.prefix = u"STEEM"
     self.default_prefix = u"STM"
     self.wif = "5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3"
     self.ref_block_num = 34294
     self.ref_block_prefix = 3707022213
     self.expiration = "2016-04-06T08:29:27"
     self.stm = Steem(offline=True)
예제 #9
0
def calculate_shares():
    global reward_share, base_share, reward_vesting, steem_per_mvest

    try:
        info = Steem().get_dynamic_global_properties()
        reward_fund = Steem().get_reward_funds()
        total_vests = Amount(info["total_vesting_shares"]).amount
        total_vesting_fund = Amount(info["total_vesting_fund_steem"]).amount
        reward_balance = Amount(reward_fund["reward_balance"]).amount
        recent_claims = float(reward_fund["recent_claims"])
        reward_share = reward_balance / recent_claims
        base_share = Amount(
            Steem().get_current_median_history()["base"]).amount
        reward_vesting = total_vesting_fund / total_vests
        steem_per_mvest = Steem().get_steem_per_mvest()
        print("- Reward Share and Base Share Actualized")
    except Exception as err:
        print("*Error Calculate Shares : %s" % err)
        pass

    return
예제 #10
0
    def get_steem_instance(self, config, keys=None):
        if not keys:
            keys = []

        logger.info("Connecting to the blockchain using mainnet.")
        nodes = config.get("NODES") or [
            "https://api.hive.blog", "https://api.hivekings.com",
            "https://anyx.io"
        ]
        steem = Steem(node=nodes, keys=keys, custom_chains=custom_chains)

        return steem
예제 #11
0
    def get_rpc(self, symbol):
        """
        Returns a Steem instance for querying data and sending TXs. By default, uses the Beem shared_steem_instance.

        If a custom RPC list is specified in the Coin "custom json" settings, a new instance will be returned with the
        RPCs specified in the json.

        :param symbol: Coin symbol to get Beem RPC instance for
        :return beem.steem.Steem: An instance of :class:`beem.steem.Steem` for querying
        """
        rpc_list = self.settings[symbol]['json'].get('rpcs')
        return self.rpc if empty(rpc_list, itr=True) else Steem(node=rpc_list)
예제 #12
0
    def __init__(self, symbol: str):
        super().__init__(symbol)
        settings = self.coin.settings['json']

        rpcs = settings.get('rpcs')
        # If you've specified custom RPC nodes in the custom JSON, make a new instance with those
        # Otherwise, use the global shared_steem_instance.
        self.rpc = shared_steem_instance() if empty(rpcs, itr=True) else Steem(
            rpcs)  # type: Steem
        self.rpc.set_password_storage(settings.get('pass_store',
                                                   'environment'))
        # Internal storage variables for the properties ``asset`` and ``precisions``
        self._asset = self._precision = None
예제 #13
0
파일: bot.py 프로젝트: sectionshankar/helpy
async def stream():
    try:
        stm = Steem(node=[
            "https://api.steemit.com",
            "https://steemd.minnowsupportproject.org", "https://anyx.io"
        ])
        chain = Blockchain(stm, "head")
        for tx in chain.stream(['custom_json']):
            if tx['id'] == 'sm_sell_cards':
                user_perm_posting = ""
                user_perm_active = ""
                try:
                    user_perm_posting = tx['required_posting_auths'][0]
                except:
                    pass
                try:
                    user_perm_active = tx['required_auths'][0]
                except:
                    pass
                json_data = json.loads(tx['json'])
                loop.create_task(
                    process(json_data, user_perm_posting, user_perm_active))
            elif tx['id'] == 'sm_update_price':
                market_id_list = json.loads(tx['json'])['ids']
                card_uid_dict = []
                for market_id in market_id_list:
                    time.sleep(2)
                    try:
                        response_json = requests.get(
                            f"https://steemmonsters.com/market/status?id={market_id}"
                        ).json()
                        card_uid = response_json['cards'][0]['uid']
                        card_uid_dict.append(card_uid)
                    except:
                        pass
                user_perm_posting = ""
                user_perm_active = ""
                try:
                    user_perm_posting = tx['required_posting_auths'][0]
                except:
                    pass
                try:
                    user_perm_active = tx['required_auths'][0]
                except:
                    pass
                loop.create_task(
                    process(card_uid_dict, user_perm_posting,
                            user_perm_active))
            await asyncio.sleep(0)
    except:
        print(traceback.format_exc())
예제 #14
0
    def __init__(self, symbol: str):
        super().__init__(symbol)
        settings = self.coin.settings['json']

        rpcs = settings.get('rpcs')
        # If you've specified custom RPC nodes in the custom JSON, make a new instance with those
        # Otherwise, use the global shared_steem_instance.
        self.rpc = shared_steem_instance() if empty(rpcs, itr=True) else Steem(
            rpcs)  # type: Steem
        self.rpc.set_password_storage(settings.get('pass_store',
                                                   'environment'))
        # For easy reference, the Beem asset object, and precision
        self.asset = asset = Asset(self.symbol)
        self.precision = int(asset.precision)
예제 #15
0
    def custom_beem(node: Union[str, list] = "", *args, **kwargs):
        """
        Override the beem Steem instance (:py:attr:`._steem`) used by this class.

        Useful if you'd rather not configure beem's shared instance for some reason.

        Example usage:

        >>> from privex.steemengine import SteemEngineToken
        >>> SteemEngineToken.custom_beem(node=['https://steemd.privex.io', 'https://api.steemit.com'])

        """
        from beem.steem import Steem
        SteemEngineToken._steem = Steem(node, *args, **kwargs)
        return SteemEngineToken._steem
예제 #16
0
def benchmark_node_history(node,
                           num_retries=10,
                           num_retries_call=10,
                           timeout=60,
                           how_many_seconds=60,
                           account_name="gtg"):
    history_count = 0
    access_time = 0
    follow_time = 0
    sucessfull = False
    error_msg = None
    start_total = timer()
    start_time = timer()

    try:
        stm = Steem(node=node,
                    num_retries=num_retries,
                    num_retries_call=num_retries_call,
                    timeout=timeout)
        account = Account(account_name, steem_instance=stm)
        start_time = timer()
        for acc_op in account.history_reverse(batch_size=100):
            history_count += 1
            if not sucessfull:
                sucessfull = True
            if timer() - start_time > how_many_seconds or quit_thread:
                break
    except NumRetriesReached:
        error_msg = 'NumRetriesReached'
        sucessfull = False
    except KeyboardInterrupt:
        error_msg = 'KeyboardInterrupt'
        sucessfull = False
        # quit = True
    except Exception as e:
        error_msg = str(e)
        sucessfull = False

    total_duration = float("{0:.2f}".format(timer() - start_time))
    return {
        'sucessfull': sucessfull,
        'node': node,
        'error': error_msg,
        'total_duration': total_duration,
        'count': history_count,
        'access_time': None
    }
예제 #17
0
def steem_sbd(key, player, token, mymoney, toplayer, memo):
    local_values.s = Steem(keys=[key])
    set_shared_steem_instance(local_values.s)
    account = Account(player)
    # 转账
    kk = account.transfer(toplayer, mymoney, token, memo)

    tx = Signed_Transaction(kk)
    tx.data.pop("signatures", None)
    print(tx)
    h = hashlib.sha256(bytes(tx)).digest()
    transaction_id = hexlify(h[:20]).decode("ascii")
    print(transaction_id)
    url = "https://steemd.com/tx/%s" % transaction_id
    print("转账完成")
    print(url)
    return url
예제 #18
0
def anyx():
    SV = os.environ.get('SV')
    di = {
        '16': .55,
        '15': .03,
        '5': .42,
        '49': .45,
        '27': .42,
        '38': .42,
        '70': .50,
        '71': .45,
        '72': .55,
        '73': .45,
        '74': .4,
    }

    dic = {'16': .7, '5': .50, '49': .7, '27': .56, '38': .68}

    stm = Steem(node="https://anyx.io", keys=SV)
    acc = Account('sourovafrin', steem_instance=stm)
    bo = Blockchain(stm, 'head')

    print("started anyx")
    for detail in bo.stream(['custom_json']):
        try:
            if detail['id'] == 'sm_sell_cards':
                for i in ast.literal_eval(detail['json']):
                    lin = requests.get(
                        "https://steemmonsters.com/cards/find?ids=" +
                        i['cards'][0]).json()
                    for ii in lin:
                        id = ii['market_id']
                        idd = str(ii['card_detail_id'])
                        price = float(ii['buy_price'])
                        if int(ii['edition']) == 1 and price <= di[idd]:
                            acc.transfer(
                                'svirus', 2, 'SBD',
                                "sm_market_purchase:" + id + ":sourovafrin")

                        elif int(ii['edition']) == 0 and price <= dic[idd]:
                            acc.transfer(
                                'svirus', 2, 'SBD',
                                "sm_market_purchase:" + id + ":sourovafrin")
        except Exception as e:
            print("Error found anyx: {}".format(e))
예제 #19
0
def main(conn, logger, debug=False):
    # Main Loop
    s = Steem(node=nodes)
    theChain = Blockchain(steem_instance=s, mode="head")

    Start_block_num = read_blocknum_fromfile("virtual_ops_block.txt")
    if not Start_block_num:
        Start_block_num = theChain.get_current_block_num()


#  print('Start For loop')
    try:
        for block in theChain.stream(only_virtual_ops=True,
                                     start=Start_block_num):
            print("Try add to DB")
            addblock_to_db(block, conn, logger)

    except Exception as e:
        return
예제 #20
0
def main(conn, logger, debug=False):
    s = Steem(node=nodes)

    theChain = Blockchain(steem_instance=s, mode="head")
    #  print('Start For loop')

    Start_block_num = read_blocknum_fromfile("ops_block.txt")
    if not Start_block_num:
        Start_block_num = theChain.get_current_block_num()

    try:
        for block in theChain.stream(start=Start_block_num):
            #      print("Run Again")
            #      print(f"{block['block_num']}")
            yay = addblock_to_db(block, conn, logger)


#      print("Got out ok")

    except Exception as e:
        logger.error(f"Error in Stream: {e}")
        return
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:
        stm = Steem(node=node)
        print(str(stm))
    else:
        stm = None
    acc_dict = {}
    for name in name_list:
        acc = Account(name, steem_instance=stm)
        acc_dict[name] = acc
        if clear_acc_cache:
            acc.clear_cache()
        acc_dict = {}
    if clear_all_cache:
        clear_cache()
    if not shared_instance:
        del stm.rpc
예제 #22
0
if __name__ == "__main__":
    how_many_minutes = 10
    how_many_virtual_op = 10000
    max_batch_size = None
    threading = False
    thread_num = 16
    nodes = get_node_list(appbase=False) + get_node_list(appbase=True)
    t = PrettyTable([
        "node", "10 blockchain minutes", "10000 virtual account op", "version"
    ])
    t.align = "l"
    for node in nodes:
        print("Current node:", node)
        try:
            stm = Steem(node=node, num_retries=3)
            blockchain = Blockchain(steem_instance=stm)
            account = Account("gtg", steem_instance=stm)
            virtual_op_count = account.virtual_op_count()
            blockchain_version = stm.get_blockchain_version()

            last_block_id = 19273700
            last_block = Block(last_block_id, steem_instance=stm)
            startTime = datetime.now()

            stopTime = last_block.time() + timedelta(seconds=how_many_minutes *
                                                     60)
            ltime = time.time()
            cnt = 0
            total_transaction = 0
예제 #23
0
from beemgraphenebase.account import PasswordKey, PrivateKey, PublicKey
from beem.steem import Steem
from beem.utils import parse_time, formatTimedelta
from beemapi.exceptions import NumRetriesReached
from beem.nodelist import NodeList
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

password = "******"
username = "******"
useWallet = False
walletpassword = "******"

if __name__ == "__main__":
    testnet_node = "https://testnet.steem.vc"
    stm = Steem(node=testnet_node)
    prefix = stm.prefix
    # curl --data "username=username&password=secretPassword" https://testnet.steem.vc/create
    if useWallet:
        stm.wallet.wipe(True)
        stm.wallet.create(walletpassword)
        stm.wallet.unlock(walletpassword)
    active_key = PasswordKey(username, password, role="active", prefix=prefix)
    owner_key = PasswordKey(username, password, role="owner", prefix=prefix)
    posting_key = PasswordKey(username, password, role="posting", prefix=prefix)
    memo_key = PasswordKey(username, password, role="memo", prefix=prefix)
    active_pubkey = active_key.get_public_key()
    owner_pubkey = owner_key.get_public_key()
    posting_pubkey = posting_key.get_public_key()
    memo_pubkey = memo_key.get_public_key()
    active_privkey = active_key.get_private_key()
예제 #24
0
accountname = 'bitcoinjake09'
myPlanet = "P-Z6AY2BGWNIO"
shipName = "corvette"
shipCount = 3
sleepAmt = (
    (3244) * 2
)  #set as (time it takes ships to get to planet + 4 seconds for steem blockchain) *2 for total mission
# can use a seconds calculator if you know your ships time from spycolony distance calculator:
# https://spycolony.herokuapp.com/calc.html
# seconds calculator: https://www.dollartimes.com/calculators/hours-minutes-calculator.htm
count = 1
# Address of person I don't like x/y
x = -24
y = 249
while (count <= 1001):
    s = Steem(node=nodes, keys=[PK])
    id = 'nextcolony'
    json_data = {
        "username": accountname,
        "type": "attack",
        "command": {
            "tr_var1": {
                shipName: {
                    "pos": 1,
                    "n": shipCount
                }
            },
            "tr_var2": x,
            "tr_var3": y,
            "tr_var4": myPlanet
        }
예제 #25
0
def benchmark_node_blocks(node,
                          num_retries=10,
                          num_retries_call=10,
                          timeout=60,
                          how_many_seconds=30):
    block_count = 0
    sucessfull = False
    error_msg = None
    start_total = timer()
    start_time = timer()
    max_batch_size = None
    threading = False
    thread_num = 16

    last_block_id = 19273700
    try:
        stm = Steem(node=node,
                    num_retries=num_retries,
                    num_retries_call=num_retries_call,
                    timeout=timeout)
        blockchain = Blockchain(steem_instance=stm)

        last_block_id = int(blockchain.get_current_block_num() * 0.75)

        last_block = Block(last_block_id, steem_instance=stm)

        total_transaction = 0

        start_time = timer()
        for entry in blockchain.blocks(start=last_block_id,
                                       max_batch_size=max_batch_size,
                                       threading=threading,
                                       thread_num=thread_num):
            block_no = entry.identifier
            block_count += 1
            if not sucessfull:
                sucessfull = True
            if "block" in entry:
                trxs = entry["block"]["transactions"]
            else:
                trxs = entry["transactions"]

            for tx in trxs:
                for op in tx["operations"]:
                    total_transaction += 1
            if "block" in entry:
                block_time = (entry["block"]["timestamp"])
            else:
                block_time = (entry["timestamp"])

            if timer() - start_time > how_many_seconds or quit_thread:
                break
    except NumRetriesReached:
        error_msg = 'NumRetriesReached'
        sucessfull = False
    except KeyboardInterrupt:
        error_msg = 'KeyboardInterrupt'
        # quit = True
    except Exception as e:
        error_msg = str(e)
        sucessfull = False
    total_duration = float("{0:.2f}".format(timer() - start_time))
    return {
        'sucessfull': sucessfull,
        'node': node,
        'error': error_msg,
        'total_duration': total_duration,
        'count': block_count,
        'access_time': None
    }
예제 #26
0
def benchmark_block_diff(node,
                         num_retries=10,
                         num_retries_call=10,
                         timeout=60):
    block_count = 0
    history_count = 0
    access_time = timeout
    follow_time = 0
    sucessfull = False
    error_msg = None
    start_total = timer()
    block_diff = 0
    block_head_diff = 0
    try:
        stm = Steem(node=node,
                    num_retries=num_retries,
                    num_retries_call=num_retries_call,
                    timeout=timeout)

        b = Blockchain(steem_instance=stm)
        b_head = Blockchain(mode="head", steem_instance=stm)
        dhi_max = 0
        head_max = timedelta(0)
        for i in range(0, 5):
            utcnow = addTzInfo(datetime.utcnow())
            df_head = addTzInfo(
                datetime.utcnow()) - b_head.get_current_block()["timestamp"]
            diff_value = b_head.get_current_block_num(
            ) - b.get_current_block_num()
            if diff_value > dhi_max:
                dhi_max = diff_value
            if df_head > head_max:
                head_max = df_head

            time.sleep(3)

        block_head_diff = head_max.total_seconds()
        block_diff = dhi_max
        sucessfull = True
    except NumRetriesReached:
        error_msg = 'NumRetriesReached'
        sucessfull = False
    except KeyboardInterrupt:
        error_msg = 'KeyboardInterrupt'
        # quit = True
    except Exception as e:
        error_msg = str(e)
        sucessfull = False
    total_duration = float("{0:.2f}".format(timer() - start_total))
    block_diff = float("{0:.2f}".format(block_diff))
    block_head_diff = float("{0:.2f}".format(block_head_diff))
    return {
        'sucessfull': sucessfull,
        'node': node,
        'error': error_msg,
        'total_duration': total_duration,
        'access_time': None,
        'count': None,
        'diff_head_irreversible': block_diff,
        'head_delay': block_head_diff
    }
예제 #27
0
from beembase import operations
from beem.transactionbuilder import TransactionBuilder
from beemgraphenebase.account import PasswordKey, PrivateKey, PublicKey
from beem.steem import Steem
from beem.utils import parse_time, formatTimedelta
from beemapi.exceptions import NumRetriesReached
from beem.nodelist import NodeList
from beembase.transactions import getBlockParams
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

# example wif
wif = "5KQwrPbwdL6PhXujxW37FSSQZ1JiwsST4cqQzDeyXtP79zkvFD3"

if __name__ == "__main__":
    stm_online = Steem()
    ref_block_num, ref_block_prefix = getBlockParams(stm_online)
    print("ref_block_num %d - ref_block_prefix %d" %
          (ref_block_num, ref_block_prefix))

    stm = Steem(offline=True)

    op = operations.Transfer({
        'from': 'beembot',
        'to': 'holger80',
        'amount': "0.001 SBD",
        'memo': ""
    })
    tb = TransactionBuilder(steem_instance=stm)

    tb.appendOps([op])
예제 #28
0
from datetime import date, datetime, timedelta
from io import StringIO
from pprint import pprint

import requests
from beem.steem import Steem
from beem.wallet import Wallet
from pandas import read_csv
from sqlalchemy import create_engine

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s %(message)s",
                    datefmt="%m/%d/%Y %I:%M:%S %p")

wif = os.environ["STEEM_WIF"]
stm = Steem(node="https://api.steemit.com", keys=wif, nobroadcast=False)
w = Wallet(blockchain_instance=stm)
author = w.getAccountFromPrivateKey(wif)
logging.debug(author)
engine = create_engine("sqlite:///covid.db")
covid_cvs = requests.get(
    "https://opendata.ecdc.europa.eu/covid19/casedistribution/csv")
yesterday = datetime.now() + timedelta(days=-1)
covid_day = yesterday.strftime("%d/%m/%Y")
df = read_csv(StringIO(covid_cvs.text))
sql = df.to_sql("Covid", con=engine, if_exists="replace")
result = engine.execute(f'SELECT * FROM Covid where dateRep="{covid_day}"')
data = result.fetchall()


def main():
예제 #29
0
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from builtins import int, str
import sys
from datetime import timedelta
import time
import io
from beem.steem import Steem
import logging
from prettytable import PrettyTable
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

if __name__ == "__main__":
    stm = Steem(node="https://api.steemit.com")
    # stm = Steem(node="https://testnet.steemitdev.com")
    # stm = Steem(node="wss://appbasetest.timcliff.com")
    # stm = Steem(node="https://api.steemitstage.com")
    # stm = Steem(node="https://api.steemitdev.com")
    all_calls = stm.rpc.get_methods(api="jsonrpc")
    t = PrettyTable(["method", "args", "ret"])
    t.align = "l"
    t_condenser = PrettyTable(["method", "args", "ret"])
    t_condenser.align = "l"
    for call in all_calls:
        if "condenser" not in call:
            ret = stm.rpc.get_signature({'method': call}, api="jsonrpc")
            t.add_row([call, ret['args'], ret['ret']])
        else:
            ret = stm.rpc.get_signature({'method': call}, api="jsonrpc")
예제 #30
0
#########
# Steem Network related settings
####
from privex.helpers import env_csv

# Supply a list of one or more comma-separated Steem RPC nodes. If not set, will use the default beem nodes.
STEEM_RPC_NODES = env_csv('STEEM_RPC_NODES', None)
# Supply a list of one or more comma-separated Steem RPC nodes. If not set, will use the default beem nodes.
HIVE_RPC_NODES = env_csv('HIVE_RPC_NODES', [
    'https://anyx.io', 'https://hived.privex.io',
    'https://hived.hive-engine.com'
])
# Set the shared Beem RPC instance to use the specified nodes
steem_ins = Steem(node=STEEM_RPC_NODES,
                  num_retries=5,
                  num_retries_call=3,
                  timeout=20)
steem_ins.set_password_storage(
    'environment')  # Get Beem wallet pass from env var ``UNLOCK``
set_shared_steem_instance(steem_ins)

# Set the shared Beem RPC instance to use the specified nodes
# hive_ins = Hive(node=HIVE_RPC_NODES, num_retries=5, num_retries_call=3, timeout=20)
# hive_ins.set_password_storage('environment')  # Get Beem wallet pass from env var ``UNLOCK``
# set_shared_hive_instance(hive_ins)

#########
# SteemEngine Handler Network related settings
####
SENG_NETWORK_ACCOUNT = env('SENG_NETWORK_ACCOUNT', 'ssc-mainnet1')