示例#1
0
    def test_export(self, node_param):
        if node_param == "normal":
            bts = self.bts
        else:
            bts = self.steemit
        owner = "gtg"
        if bts.rpc.get_use_appbase():
            witness = bts.rpc.find_witnesses({'owners': [owner]},
                                             api="database")['witnesses']
            if len(witness) > 0:
                witness = witness[0]
        else:
            witness = bts.rpc.get_witness_by_account(owner)

        w = Witness(owner, steem_instance=bts)
        keys = list(witness.keys())
        json_witness = w.json()
        exclude_list = [
            'votes', 'virtual_last_update', 'virtual_scheduled_time',
            'last_aslot', 'last_confirmed_block_num'
        ]
        for k in keys:
            if k not in exclude_list:
                if isinstance(witness[k], dict) and isinstance(
                        json_witness[k], list):
                    self.assertEqual(list(witness[k].values()),
                                     json_witness[k])
                else:
                    self.assertEqual(witness[k], json_witness[k])
示例#2
0
 def witness_json(self, name):
     try:
         w = Witness(name)
     except WitnessDoesNotExistsException:
         self.log.log("Witness does not exist.", 2)
         return False
     return w.json()
示例#3
0
 def pubfeed(self, price):
     if self.locked():
         self.unlock_wallet()
     w = Witness(self.conf.d['owner'])
     if w.feed_publish(base=price, quote="1.000 STEEM"):
         logstr = "Feed published: {:.3f} SBD/STEEM".format(price)
         self.log.log(logstr, 1)
示例#4
0
    def test_Witness(self):
        with self.assertRaises(exceptions.WitnessDoesNotExistsException):
            Witness("FOObarNonExisting")

        c = Witness("jesta")
        self.assertEqual(c["owner"], "jesta")
        self.assertIsInstance(c.account, Account)
示例#5
0
 def update(self, enable=True, key=''):
     if not self.__wallet_hook():
         return False
     w = Witness(self.conf.d['owner'])
     if enable:
         if key:
             if w.update(key,
                         self.conf.d['url'],
                         self.conf.d['props'],
                         account=self.conf.d['owner']):  # pragma: no cover
                 self.log.log("Witness updated with new parameters.", 2)
                 return True
         else:
             if w.update(self.conf.d['pub_key'],
                         self.conf.d['url'],
                         self.conf.d['props'],
                         account=self.conf.d['owner']):  # pragma: no cover
                 self.log.log("Witness updated with new parameters.", 2)
                 return True
     else:
         if w.update(DISABLE_KEY,
                     self.conf.d['url'],
                     self.conf.d['props'],
                     account=self.conf.d['owner']):  # pragma: no cover
             self.log.log("Witness disabled.", 1)
             return True
示例#6
0
 def pubfeed(self, price):
     if not self.__wallet_hook():
         return False
     w = Witness(self.conf.d['owner'])
     if w.feed_publish(base=price, quote="1.000 STEEM"):
         logstr = "Feed published: {:.3f} SBD/STEEM".format(price)
         self.log.log(logstr, 1)
         return True
示例#7
0
 def change_key(self, pub_key):
     if self.stm.wallet.locked():
         self.unlock_wallet()
     w = Witness(self.conf.d['owner'])
     if w.update(pub_key,
                 self.conf.d['url'],
                 self.conf.d['props'],
                 account=self.conf.d['owner']):
         logstr = "Witness public key updated to {}.".format(pub_key)
         self.log.log(logstr, 1)
示例#8
0
 def test_feed_publish(self, node_param):
     if node_param == "non_appbase":
         bts = self.bts
     else:
         bts = self.appbase
     bts.txbuffer.clear()
     w = Witness("gtg", steem_instance=bts)
     tx = w.feed_publish("4 SBD", "1 STEEM")
     self.assertEqual((tx["operations"][0][0]), "feed_publish")
     op = tx["operations"][0][1]
     self.assertIn("gtg", op["publisher"])
示例#9
0
文件: config.py 项目: bobinson/pywit
 def check_config(self, name):
     self.d['owner'] = name
     try:
         w = Witness(name)
     except WitnessDoesNotExistsException:
         return False
     wj = w.json()
     self.d['props'] = wj['props']
     self.d['url'] = wj['url']
     self.write_config()
     return True
示例#10
0
 def test_feed_publish(self, node_param):
     if node_param == "normal":
         bts = self.bts
     else:
         bts = self.steemit
     bts.txbuffer.clear()
     w = Witness("gtg", steem_instance=bts)
     tx = w.feed_publish("4 %s" % bts.backed_token_symbol,
                         "1 %s" % bts.token_symbol)
     self.assertEqual((tx["operations"][0][0]), "feed_publish")
     op = tx["operations"][0][1]
     self.assertIn("gtg", op["publisher"])
示例#11
0
 def get_price_feed(self, name=''):
     try:
         if name:
             wjson = Witness(name).json()
             p = (float(wjson['sbd_exchange_rate']['base']['amount']) /
                  10**wjson['sbd_exchange_rate']['base']['precision'])
         else:
             wjson = Witness(self.conf.d['owner']).json()
             p = (float(wjson['sbd_exchange_rate']['base']['amount']) /
                  10**wjson['sbd_exchange_rate']['base']['precision'])
     except WitnessDoesNotExistsException:
         return False
     return p
示例#12
0
 def change_key(self, pub_key):
     if not self.__wallet_hook():
         return False
     w = Witness(self.conf.d['owner'])
     if pub_key:
         if w.update(pub_key,
                     self.conf.d['url'],
                     self.conf.d['props'],
                     account=self.conf.d['owner']):
             logstr = "Witness public key updated to {}.".format(pub_key)
             self.log.log(logstr, 1)
             return True
     else:
         return False
示例#13
0
 def test_update(self, node_param):
     if node_param == "non_appbase":
         bts = self.bts
     else:
         bts = self.appbase
     w = Witness("gtg", steem_instance=bts)
     props = {"account_creation_fee": "0.1 STEEM",
              "maximum_block_size": 32000,
              "sbd_interest_rate": 0}
     tx = w.update(wif, "", props)
     self.assertEqual((tx["operations"][0][0]), "witness_update")
     op = tx["operations"][0][1]
     self.assertIn(
         "gtg",
         op["owner"])
示例#14
0
 def test_witness(self, node_param):
     if node_param == "instance":
         stm = Steem(node="abc", autoconnect=False, num_retries=1)
         set_shared_steem_instance(self.bts)
         o = Witness("gtg")
         self.assertIn(o.steem.rpc.url, self.urls)
         with self.assertRaises(NumRetriesReached):
             Witness("gtg", steem_instance=stm)
     else:
         set_shared_steem_instance(
             Steem(node="abc", autoconnect=False, num_retries=1))
         stm = self.bts
         o = Witness("gtg", steem_instance=stm)
         self.assertIn(o.steem.rpc.url, self.urls)
         with self.assertRaises(NumRetriesReached):
             Witness("gtg")
示例#15
0
    def __init__(self, username):
        self.username = username
        self.account = None
        self.witness = 0
        self.nodes = [
            'https://rpc.blurt.buzz',
            # 'https://blurtd.privex.io',
            # 'https://rpc.blurtworld.com',
            # 'https://rpc.blurt.world',
            # 'https://api.softmetal.xyz',
        ]
        random.shuffle(self.nodes)

        self.blurt = Blurt(node=self.nodes)
        self.blockchain = set_shared_blockchain_instance(self.blurt)

        # Get a reference to the database service
        self.firebase = firebase.database()

        # Create account object
        try:
            self.account = Account(self.username, full=False, lazy=False)
        except Exception as e:
            self.username = None
            self.account = None
            print(f'AccountDoesNotExistsException : {e}')

        # Witness check
        try:
            Witness(self.username)
            self.witness = 1
        except Exception:
            self.witness = 0
示例#16
0
 def test_update(self, node_param):
     if node_param == "normal":
         bts = self.bts
     else:
         bts = self.steemit
     bts.txbuffer.clear()
     w = Witness("gtg", steem_instance=bts)
     props = {
         "account_creation_fee": "0.1 %s" % bts.token_symbol,
         "maximum_block_size": 32000,
         "sbd_interest_rate": 0
     }
     tx = w.update(wif, "", props)
     self.assertEqual((tx["operations"][0][0]), "witness_update")
     op = tx["operations"][0][1]
     self.assertIn("gtg", op["owner"])
示例#17
0
 def check_key(self, name, key):
     try:
         w = Witness(name)
     except WitnessDoesNotExistsException:
         self.log.log("Witness does not exist.", 2)
         return False
     if key == w['signing_key']:
         return True
     return False
示例#18
0
 def test_witness(self, node_param):
     if node_param == "instance":
         set_shared_steem_instance(self.bts)
         o = Witness("gtg")
         self.assertIn(o.steem.rpc.url, self.urls)
         with self.assertRaises(
             RPCConnection
         ):
             Witness("gtg", steem_instance=Steem(node="https://abc.d", autoconnect=False, num_retries=1))
     else:
         set_shared_steem_instance(Steem(node="https://abc.d", autoconnect=False, num_retries=1))
         stm = self.bts
         o = Witness("gtg", steem_instance=stm)
         self.assertIn(o.steem.rpc.url, self.urls)
         with self.assertRaises(
             RPCConnection
         ):
             Witness("gtg")
示例#19
0
def checkwit(username):
    try:
        wit = Witness(username, steem_instance=stmf)
    except Exception as exception:
        assert type(exception).__name__ == 'WitnessDoesNotExistsException'
        assert exception.__class__.__name__ == 'WitnessDoesNotExistsException'
        return False
    else:
        return True
示例#20
0
    def __init__(self,
                 config_file,
                 action=None,
                 signing_key=None,
                 active_key=None,
                 witness_account=None,
                 url=None,
                 markets=None,
                 peg_multiplier=None):

        self.config = self.get_config(config_file)
        self.steem = self.get_steem_instance(self.config, keys=None)

        # Private signing key
        if signing_key:
            self.signing_key = PrivateKey(signing_key)
            logger.info(f"Got the SIGNING_KEY in the parameters.")
        else:
            self.signing_key = self._get_config_key('SIGNING_KEY', is_key=True)
        # Convert the witness account string into beem.Witness
        if witness_account:
            self.witness_account = witness_account
            logger.info("Got the WITNESS_ACCOUNT in the parameters.")
        else:
            self.witness_account = self._get_config_key('WITNESS_ACCOUNT')
        self.witness_account = Witness(self.witness_account,
                                       steem_instance=self.steem)

        if action != "publish_feed":
            # register the witness URL
            if url:
                logger.info("Got the URL in the parameters.")
                self.url = url
            else:
                self.url = self._get_config_key('URL')

        # register the active key if it's passed by CLI.
        self.active_key = active_key

        # market list to publish price feeds
        self.markets = markets
        if action == "publish_feed" and not markets:
            self.markets = self._get_config_key('MARKETS', ask_to_stdin=False)
            if not self.markets:
                self.markets = DEFAULT_MARKETS
            if not is_marketlist_valid(self.markets):
                logger.error("Invalid market list")
                sys.exit(0)
        if self.markets and not isinstance(self.markets, list):
            # convert comma separated string into list
            self.markets = list(
                map(lambda x: x.strip(), self.markets.split(",")))

        self.peg_multiplier = peg_multiplier or 1
示例#21
0
 def update(self, enable=True, key=''):
     if self.stm.wallet.locked():
         self.unlock_wallet()
     w = Witness(self.conf.d['owner'])
     if enable:
         if key:
             if w.update(key,
                         self.conf.d['url'],
                         self.conf.d['props'],
                         account=self.conf.d['owner']):
                 self.log.log("Witness updated with new parameters.", 2)
         else:
             if w.update(self.conf.d['pub_key'],
                         self.conf.d['url'],
                         self.conf.d['props'],
                         account=self.conf.d['owner']):
                 self.log.log("Witness updated with new parameters.", 2)
     else:
         if w.update(DISABLE_KEY,
                     self.conf.d['url'],
                     self.conf.d['props'],
                     account=self.conf.d['owner']):
             self.log.log("Witness disabled.", 1)
示例#22
0
 def get_missed(self, name=''):
     try:
         if name:
             w = Witness(name)
             m = w.json()['total_missed']
         else:
             w = Witness(self.conf.d['owner'])
             m = w.json()['total_missed']
     except WitnessDoesNotExistsException:
         return False
     return m
示例#23
0
 def print_witness(self, name=''):
     if name:
         try:
             w = Witness(name)
         except WitnessDoesNotExistsException:
             self.log.log("Witness does not exist.", 2)
             return False
         self.conf.print_json(w.json())
     else:
         try:
             w = Witness(self.conf.d['owner'])
         except WitnessDoesNotExistsException:
             self.log.log("Witness does not exist.", 2)
             return False
         self.conf.print_json(w.json())
threshold = 10  #Number of total blocks missed to activate killswitch.

stm = Steem(
    node=["https://peer.vit.tube/"],
    bundle=True,
    blocking="head",
    nobroadcast=True,  #set True for testing
    custom_chains=CUSTOM_CHAINS,
    #keys={'active': wif},
)

while True:
    try:
        set_shared_steem_instance(stm)
        currentdatetime = datetime.datetime.now()
        w1 = Witness(acct)
        json_string = json.dumps(w1.json(), indent=4)
        data = json.loads(json_string)
        total_missed = data["total_missed"]
        print(currentdatetime.strftime("%a %b %d %Y - %I:%M:%S %p"))
        print("Witness " + acct + " current total missed: " +
              str(total_missed))
        if total_missed >= threshold:
            print(
                "Total missed at or above threshold. Disabling witness server."
            )
            #Disable witness.
            tx = TransactionBuilder(steem_instance=stm)
            update_witness = {
                "owner": acct,
                "url": "No website yet",
示例#25
0
 def get_missed(self):
     w = Witness(self.conf.d['owner'])
     m = w.json()['total_missed']
     return m
示例#26
0
parser.add_argument('--creationfee',
                    help="Account creation fee to advertise as a witness",
                    type=str)
parser.add_argument('--blocksize',
                    help="Blocksize to advertise as a witness",
                    type=int)
parser.add_argument('--interestrate',
                    help="Interest rate to advertise as a witness",
                    type=int)
args = parser.parse_args()
if (args.operation[0] == "update"):
    if checkwit(args.account[0]):
        if not checkkey(args.account[0], args.privateactivekey[0], "active"):
            sys.exit("Private active key " + args.privateactivekey[0] +
                     " doesn't prove authority for user " + args.account[0])
        wit = Witness(args.account[0], steem_instance=stmf)
        #Witness exists
        #take stuff from blockchain, if the user doesn't provide the args
        if not args.publicownerkey:
            my_publickey = str(wit.json()["signing_key"])
        else:
            try:
                PublicKey(args.publicownerkey, prefix="EUR")
            except:
                sys.exit("Wrong public key syntax " + args.publicownerkey)
            else:
                my_publickey = str(args.publicownerkey)

        if not args.url:
            my_url = str(wit.json()["url"])
        else:
示例#27
0
 def test_witness(self):
     o = Witness("gtg")
     self.assertEqual(o.steem.rpc.url, self.url)
示例#28
0
    else:
        blk_auths_public[role] = str(account.json()[role]["key_auths"][0][0])

    if publickey == blk_auths_public[role]:
        return True
    else:
        return False

parser = ArgumentParser()
parser.add_argument('witness', help="Name of the Pulsar Witness", type=str, nargs=1)
parser.add_argument('privateactivekey', help="Private active key of the Witness", type=str, nargs=1)
parser.add_argument('baseprice', help="New feed price in EUR to publish for a 1.000 Pulsar quote. E.G.: \"4.700\"", type=float, nargs=1)
args = parser.parse_args()

if checkwit(args.witness[0]):
    if not checkkey(args.witness[0], args.privateactivekey[0], "active"): sys.exit("Private active key " + args.privateactivekey[0] + " doesn't prove authority for Witness " + args.witness[0])
    #Witness exists
    stm = Steem(node=["https://apidev.blkcc.xyz"])
    set_shared_steem_instance(stm)

    my_feed = "{:.3f} EUR".format(args.baseprice[0])
    wit = Witness(args.witness[0])

    output = wit.feed_publish(my_feed)
    print(json.dumps(output, indent=4))

else:
     sys.exit("The account provided is not a valid witness in the Pulsar Blockchain. Wrong witness " + args.account[0])

# vim: set filetype=sh ts=4 sw=4 tw=0 wrap et:
示例#29
0
    elif next_block_h > 1:
        time_diff_est = "%.2f hours" % next_block_h
    elif next_block_min > 1:
        time_diff_est = "%.2f minutes" % next_block_min
    else:
        time_diff_est = "%.2f seconds" % next_block_s
    return time_diff_est


if __name__ == "__main__":
    if len(sys.argv) != 2:
        witness = "holger80"
    else:
        witness = sys.argv[1]
    stm = Steem()
    witness = Witness(witness, steem_instance=stm)

    witness_schedule = stm.get_witness_schedule()
    config = stm.get_config()
    if "VIRTUAL_SCHEDULE_LAP_LENGTH2" in config:
        lap_length = int(config["VIRTUAL_SCHEDULE_LAP_LENGTH2"])
    else:
        lap_length = int(config["STEEM_VIRTUAL_SCHEDULE_LAP_LENGTH2"])
    witnesses = WitnessesRankedByVote(limit=250, steem_instance=stm)
    vote_sum = witnesses.get_votes_sum()

    virtual_time_to_block_num = int(
        witness_schedule["num_scheduled_witnesses"]) / (lap_length /
                                                        (vote_sum + 1))
    while True:
        witness.refresh()
示例#30
0
stm = Steem(
	node=["https://peer.vit.tube/"],
	bundle=True,
	blocking="head",
	nobroadcast=NO_BROADCAST, #set True for testing	
	custom_chains=CUSTOM_CHAINS,
	keys={'active': WIF},
)

#stm.wallet.unlock(UNLOCK)

while True:
  try:
    set_shared_steem_instance(stm)
    currentdatetime = datetime.datetime.now()
    w1 = Witness(ACCT)
    json_string = json.dumps(w1.json(), indent=4)
    data = json.loads(json_string)
    total_missed = data["total_missed"]
    if total_missed >= THRESHOLD:
	  #Disable witness.
      tx = TransactionBuilder(steem_instance=stm)
      update_witness = {
        "owner": ACCT,
        "url": "No website yet", 
        "block_signing_key": NATIVE_PREFIX + '1111111111111111111111111111111114T1Anm', 
        "props": {
          "account_creation_fee": Amount("0.100 %s" % (NATIVE_SYMBOL)),
          "maximum_block_size":131072, 
        },
      "fee": Amount("0.000 %s" % (NATIVE_SYMBOL)),