Beispiel #1
0
    def _get_config_key(self, config_key, is_key=False, ask_to_stdin=True):

        # check config file
        if config_key in self.config:
            logger.info(f"Got the {config_key} in the config file.")
            if is_key:
                return PrivateKey(self.config.get(config_key))
            else:
                return self.config.get(config_key)

        # check the environment vars
        config_val = os.getenv(ENV_KEYS[config_key])
        if config_val:
            logger.info(f"Got the {config_key} in the environment vars.")
            if is_key:
                return PrivateKey(config_val)
            return config_val

        if not ask_to_stdin:
            return None

        if is_key:
            config_val = PrivateKey(getpass.getpass(f"{config_key}:\n"))
        else:
            config_val = input(f"{config_key}:\n")

        return config_val
Beispiel #2
0
 def test_btsprivkey(self):
     self.assertEqual([
         format(
             PrivateKey(
                 "5HqUkGuo62BfcJU5vNhTXKJRXuUi9QSE6jp8C3uBJ2BVHtB8WSd").
             address, "BTS"),
         format(
             PrivateKey(
                 "5JWcdkhL3w4RkVPcZMdJsjos22yB5cSkPExerktvKnRNZR5gx1S").
             address, "BTS"),
         format(
             PrivateKey(
                 "5HvVz6XMx84aC5KaaBbwYrRLvWE46cH6zVnv4827SBPLorg76oq").
             address, "BTS"),
         format(
             PrivateKey(
                 "5Jete5oFNjjk3aUMkKuxgAXsp7ZyhgJbYNiNjHLvq5xzXkiqw7R").
             address, "BTS"),
         format(
             PrivateKey(
                 "5KDT58ksNsVKjYShG4Ls5ZtredybSxzmKec8juj7CojZj6LPRF7").
             address, "BTS")
     ], [
         "BTSFN9r6VYzBK8EKtMewfNbfiGCr56pHDBFi",
         "BTSdXrrTXimLb6TEt3nHnePwFmBT6Cck112",
         "BTSJQUAt4gz4civ8gSs5srTK4r82F7HvpChk",
         "BTSFPXXHXXGbyTBwdKoJaAPXRnhFNtTRS4EL",
         "BTS3qXyZnjJneeAddgNDYNYXbF7ARZrRv5dr",
     ])
Beispiel #3
0
    def test_wallet_keys(self):
        stm = self.bts
        stm.wallet.unlock("123")
        priv_key = stm.wallet.getPrivateKeyForPublicKey(
            str(PrivateKey(self.posting_key, prefix=stm.prefix).pubkey))
        self.assertEqual(str(priv_key), self.posting_key)
        priv_key = stm.wallet.getKeyForAccount("beem", "active")
        self.assertEqual(str(priv_key), self.active_key)
        priv_key = stm.wallet.getKeyForAccount("beem1", "posting")
        self.assertEqual(str(priv_key), self.posting_key1)

        priv_key = stm.wallet.getPrivateKeyForPublicKey(
            str(
                PrivateKey(self.active_private_key_of_beem4,
                           prefix=stm.prefix).pubkey))
        self.assertEqual(str(priv_key), self.active_private_key_of_beem4)
        priv_key = stm.wallet.getKeyForAccount("beem4", "active")
        self.assertEqual(str(priv_key), self.active_private_key_of_beem4)

        priv_key = stm.wallet.getPrivateKeyForPublicKey(
            str(
                PrivateKey(self.active_private_key_of_beem5,
                           prefix=stm.prefix).pubkey))
        self.assertEqual(str(priv_key), self.active_private_key_of_beem5)
        priv_key = stm.wallet.getKeyForAccount("beem5", "active")
        self.assertEqual(str(priv_key), self.active_private_key_of_beem5)
Beispiel #4
0
    def encrypt(self,
                memo,
                bts_encrypt=False,
                return_enc_memo_only=False,
                nonce=None):
        """ Encrypt a memo

            :param str memo: clear text memo message
            :param bool return_enc_memo_only: When True, only the encoded memo is returned
            :param str nonce: when not set, a random string is generated and used
            :returns: encrypted memo
            :rtype: dict
        """
        if not memo:
            return None
        if nonce is None:
            nonce = str(random.getrandbits(64))
        if isinstance(self.from_account, Account):
            memo_wif = self.blockchain.wallet.getPrivateKeyForPublicKey(
                self.from_account["memo_key"])
            memo_wif = PrivateKey(memo_wif)
        else:
            memo_wif = self.from_account
        if isinstance(self.to_account, Account):
            pubkey = self.to_account["memo_key"]
        else:
            pubkey = self.to_account
        if not memo_wif:
            raise MissingKeyError("Memo key for %s missing!" %
                                  self.from_account["name"])

        if not hasattr(self, 'chain_prefix'):
            self.chain_prefix = self.blockchain.prefix

        if bts_encrypt:
            enc = BtsMemo.encode_memo_bts(
                PrivateKey(memo_wif),
                PublicKey(pubkey, prefix=self.chain_prefix), nonce, memo)

            return {
                "message": enc,
                "nonce": nonce,
                "from": str(PrivateKey(memo_wif).pubkey),
                "to": str(pubkey)
            }
        else:
            enc = BtsMemo.encode_memo(PrivateKey(memo_wif),
                                      PublicKey(pubkey,
                                                prefix=self.chain_prefix),
                                      nonce,
                                      memo,
                                      prefix=self.chain_prefix)
            if return_enc_memo_only:
                return enc
            return {
                "message": enc,
                "from": str(PrivateKey(memo_wif).pubkey),
                "to": str(pubkey)
            }
Beispiel #5
0
    def decrypt(self, memo):
        """ Decrypt a memo

            :param str memo: encrypted memo message
            :returns: encrypted memo
            :rtype: str
        """
        if not memo:
            return None

        # We first try to decode assuming we received the memo
        if isinstance(memo, dict) and "to" in memo and "from" in memo and "memo" in memo:
            memo_to = Account(memo["to"], steem_instance=self.steem)
            memo_from = Account(memo["from"], steem_instance=self.steem)
            message = memo["memo"]
        else:
            memo_to = self.to_account
            memo_from = self.from_account
            message = memo
        if isinstance(memo, dict) and "nonce" in memo:
            nonce = memo.get("nonce")
        else:
            nonce = ""

        try:
            memo_wif = self.steem.wallet.getPrivateKeyForPublicKey(
                memo_to["memo_key"]
            )
            pubkey = memo_from["memo_key"]
        except MissingKeyError:
            try:
                # if that failed, we assume that we have sent the memo
                memo_wif = self.steem.wallet.getPrivateKeyForPublicKey(
                    memo_from["memo_key"]
                )
                pubkey = memo_to["memo_key"]
            except MissingKeyError:
                # if all fails, raise exception
                raise MissingKeyError(
                    "Non of the required memo keys are installed!"
                    "Need any of {}".format(
                    [memo_to["name"], memo_from["name"]]))

        if not hasattr(self, 'chain_prefix'):
            self.chain_prefix = self.steem.prefix

        if message[0] == '#':
            return BtsMemo.decode_memo(
                PrivateKey(memo_wif),
                message
            )
        else:
            return BtsMemo.decode_memo_bts(
                PrivateKey(memo_wif),
                PublicKey(pubkey, prefix=self.chain_prefix),
                nonce,
                message
            )
Beispiel #6
0
 def test_btcprivkeystr(self):
     self.assertEqual([str(BitcoinAddress.from_pubkey(PrivateKey("5HvVz6XMx84aC5KaaBbwYrRLvWE46cH6zVnv4827SBPLorg76oq").pubkey)),
                       str(BitcoinAddress.from_pubkey(PrivateKey("5Jete5oFNjjk3aUMkKuxgAXsp7ZyhgJbYNiNjHLvq5xzXkiqw7R").pubkey, compressed=True)),
                       str(BitcoinAddress.from_pubkey(PrivateKey("5KDT58ksNsVKjYShG4Ls5ZtredybSxzmKec8juj7CojZj6LPRF7").pubkey, compressed=False)),
                       ],
                      ["1G7qw8FiVfHEFrSt3tDi6YgfAdrDrEM44Z",
                       "1E2jXCkSmLxirL31gHwi1UWTjUBxCgS7pq",
                       "1Gu5191CVHmaoU3Zz3prept87jjnpFDrXL",
                       ])
Beispiel #7
0
 def test_btcprivkey(self):
     self.assertEqual([format(PrivateKey("5HvVz6XMx84aC5KaaBbwYrRLvWE46cH6zVnv4827SBPLorg76oq").uncompressed.address, "BTC"),
                       format(PrivateKey("5Jete5oFNjjk3aUMkKuxgAXsp7ZyhgJbYNiNjHLvq5xzXkiqw7R").uncompressed.address, "BTC"),
                       format(PrivateKey("5KDT58ksNsVKjYShG4Ls5ZtredybSxzmKec8juj7CojZj6LPRF7").uncompressed.address, "BTC"),
                       ],
                      ["1G7qw8FiVfHEFrSt3tDi6YgfAdrDrEM44Z",
                       "12c7KAAZfpREaQZuvjC5EhpoN6si9vekqK",
                       "1Gu5191CVHmaoU3Zz3prept87jjnpFDrXL",
                       ])
Beispiel #8
0
 def test_gphprivkeystr(self):
     self.assertEqual([str(Address.from_pubkey(PrivateKey("5HvVz6XMx84aC5KaaBbwYrRLvWE46cH6zVnv4827SBPLorg76oq").pubkey)),
                       str(Address.from_pubkey(PrivateKey("5Jete5oFNjjk3aUMkKuxgAXsp7ZyhgJbYNiNjHLvq5xzXkiqw7R").pubkey, compressed=True)),
                       str(Address.from_pubkey(PrivateKey("5KDT58ksNsVKjYShG4Ls5ZtredybSxzmKec8juj7CojZj6LPRF7").pubkey, compressed=False, prefix="BTS")),
                       ],
                      ["STMBXqRucGm7nRkk6jm7BNspTJTWRtNcx7k5",
                       "STM5tTDDR6M3mkcyVv16edsw8dGUyNQZrvKU",
                       "BTS4XPkBqYw882fH5aR5S8mMKXCaZ1yVA76f",
                       ])
Beispiel #9
0
 def test_create_account(self):
     bts = Hive(node=self.nodelist.get_hive_nodes(),
                nobroadcast=True,
                unsigned=True,
                data_refresh_time_seconds=900,
                keys={
                    "active": wif,
                    "owner": wif,
                    "memo": wif
                },
                num_retries=10)
     core_unit = "STM"
     name = ''.join(
         random.choice(string.ascii_lowercase) for _ in range(12))
     key1 = PrivateKey()
     key2 = PrivateKey()
     key3 = PrivateKey()
     key4 = PrivateKey()
     key5 = PrivateKey()
     bts.txbuffer.clear()
     tx = bts.create_account(
         name,
         creator="test",  # 1.2.7
         owner_key=format(key1.pubkey, core_unit),
         active_key=format(key2.pubkey, core_unit),
         posting_key=format(key3.pubkey, core_unit),
         memo_key=format(key4.pubkey, core_unit),
         additional_owner_keys=[format(key5.pubkey, core_unit)],
         additional_active_keys=[format(key5.pubkey, core_unit)],
         additional_posting_keys=[format(key5.pubkey, core_unit)],
         additional_owner_accounts=["test1"],  # 1.2.0
         additional_active_accounts=["test2"],
         additional_posting_accounts=["test3"],
         storekeys=False,
     )
     self.assertEqual(tx["operations"][0][0], "account_create")
     op = tx["operations"][0][1]
     role = "active"
     self.assertIn(format(key5.pubkey, core_unit),
                   [x[0] for x in op[role]["key_auths"]])
     self.assertIn(format(key5.pubkey, core_unit),
                   [x[0] for x in op[role]["key_auths"]])
     self.assertIn("test2", [x[0] for x in op[role]["account_auths"]])
     role = "posting"
     self.assertIn(format(key5.pubkey, core_unit),
                   [x[0] for x in op[role]["key_auths"]])
     self.assertIn(format(key5.pubkey, core_unit),
                   [x[0] for x in op[role]["key_auths"]])
     self.assertIn("test3", [x[0] for x in op[role]["account_auths"]])
     role = "owner"
     self.assertIn(format(key5.pubkey, core_unit),
                   [x[0] for x in op[role]["key_auths"]])
     self.assertIn(format(key5.pubkey, core_unit),
                   [x[0] for x in op[role]["key_auths"]])
     self.assertIn("test1", [x[0] for x in op[role]["account_auths"]])
     self.assertEqual(op["creator"], "test")
Beispiel #10
0
 def test_derive_child(self):
     # NOTE: this key + offset pair is particularly nasty, as
     # the resulting derived value is less then 64 bytes long.
     # Thus, this test also tests for proper padding.
     p = PrivateKey("5K6hMUtQB2xwjuz3SRR6uM5HNERWgBqcK7gPPZ31XtAyBNoATZd")
     p2 = p.child(
         b"\xaf\x8f: \xf6T?V\x0bM\xd8\x16 \xfd\xde\xe9\xb9\xac\x03\r\xba\xb2\x8d\x868-\xc2\x90\x80\xe8\x1b\xce"
     )
     self.assertEqual(
         repr(p2), "0c5fae344a513a4cfab312b24c08df2b2d6afa25c0ead0d3d1d0d3e76794109b"
     )
Beispiel #11
0
    def encrypt(self, memo, bts_encrypt=False):
        """ Encrypt a memo

            :param str memo: clear text memo message
            :returns: encrypted memo
            :rtype: str
        """
        if not memo:
            return None

        nonce = str(random.getrandbits(64))
        memo_wif = self.steem.wallet.getPrivateKeyForPublicKey(
            self.from_account["memo_key"]
        )
        if not memo_wif:
            raise MissingKeyError("Memo key for %s missing!" % self.from_account["name"])

        if not hasattr(self, 'chain_prefix'):
            self.chain_prefix = self.steem.prefix

        if bts_encrypt:
            enc = BtsMemo.encode_memo_bts(
                PrivateKey(memo_wif),
                PublicKey(
                    self.to_account["memo_key"],
                    prefix=self.chain_prefix
                ),
                nonce,
                memo
            )

            return {
                "message": enc,
                "nonce": nonce,
                "from": self.from_account["memo_key"],
                "to": self.to_account["memo_key"]
            }
        else:
            enc = BtsMemo.encode_memo(
                PrivateKey(memo_wif),
                PublicKey(
                    self.to_account["memo_key"],
                    prefix=self.chain_prefix
                ),
                nonce,
                memo,
                prefix=self.chain_prefix
            )

            return {
                "message": enc,
                "from": self.from_account["memo_key"],
                "to": self.to_account["memo_key"]
            }
Beispiel #12
0
 def test_Privatekey_derive(self):
     p1 = PrivateKey("5HvVz6XMx84aC5KaaBbwYrRLvWE46cH6zVnv4827SBPLorg76oq")
     p2 = PrivateKey("5Jete5oFNjjk3aUMkKuxgAXsp7ZyhgJbYNiNjHLvq5xzXkiqw7R")
     self.assertEqual([format(p1.child(p2.get_secret()), "STM"),
                       format(p2.child(p1.get_secret()), "STM"),
                       format(p1.derive_private_key(0), "STM"),
                       format(p2.derive_private_key(56), "STM")],
                      ["STMZiwJpC7MUmc9gn3vii3XS36nUceYEfKvFC1NLSrjB7ZRQJ7gt",
                       "STM24hzNSDZYgm9C85yxJqyk32DwjXg8pCgkGVzB77hvP2XxGDdvr",
                       "STM2e99iqVQUFij7Dk2nWVNC1dL8M86q37Nj4KwPHKBu1Yy49HkwA",
                       "STMgqaH9RdvUtVk7NFnx4BZJRrNS7Lj35qaueAeYJ3tKEqPaLwa4"])
Beispiel #13
0
    def test_shared_secrets_equal(self):

        wifs = cycle([x[0] for x in test_shared_secrets])

        for i in range(len(test_shared_secrets)):
            sender_private_key = PrivateKey(next(wifs))
            sender_public_key = sender_private_key.pubkey
            receiver_private_key = PrivateKey(next(wifs))
            receiver_public_key = receiver_private_key.pubkey

            self.assertEqual(
                get_shared_secret(sender_private_key, receiver_public_key),
                get_shared_secret(receiver_private_key, sender_public_key))
Beispiel #14
0
 def test_Privatekey_pubkey(self):
     self.assertEqual([
         format(
             PrivateKey(
                 "5HvVz6XMx84aC5KaaBbwYrRLvWE46cH6zVnv4827SBPLorg76oq").
             pubkey, "STX"),
         str(
             PrivateKey(
                 "5HvVz6XMx84aC5KaaBbwYrRLvWE46cH6zVnv4827SBPLorg76oq",
                 prefix="STX").pubkey)
     ], [
         "STX7W5qsanXHgRAZPijbrLMDwX6VmHqUdL2s8PZiYKD5h1R7JaqRJ",
         "STX7W5qsanXHgRAZPijbrLMDwX6VmHqUdL2s8PZiYKD5h1R7JaqRJ"
     ])
Beispiel #15
0
 def test_create_account(self):
     bts = self.bts
     name = ''.join(random.choice(string.ascii_lowercase) for _ in range(12))
     key1 = PrivateKey()
     key2 = PrivateKey()
     key3 = PrivateKey()
     key4 = PrivateKey()
     key5 = PrivateKey()
     tx = bts.create_account(
         name,
         creator="beem",
         owner_key=format(key1.pubkey, core_unit),
         active_key=format(key2.pubkey, core_unit),
         posting_key=format(key3.pubkey, core_unit),
         memo_key=format(key4.pubkey, core_unit),
         additional_owner_keys=[format(key5.pubkey, core_unit)],
         additional_active_keys=[format(key5.pubkey, core_unit)],
         additional_owner_accounts=["beem1"],  # 1.2.0
         additional_active_accounts=["beem1"],
         storekeys=False
     )
     self.assertEqual(
         tx["operations"][0][0],
         "account_create"
     )
     op = tx["operations"][0][1]
     role = "active"
     self.assertIn(
         format(key5.pubkey, core_unit),
         [x[0] for x in op[role]["key_auths"]])
     self.assertIn(
         format(key5.pubkey, core_unit),
         [x[0] for x in op[role]["key_auths"]])
     self.assertIn(
         "beem1",
         [x[0] for x in op[role]["account_auths"]])
     role = "owner"
     self.assertIn(
         format(key5.pubkey, core_unit),
         [x[0] for x in op[role]["key_auths"]])
     self.assertIn(
         format(key5.pubkey, core_unit),
         [x[0] for x in op[role]["key_auths"]])
     self.assertIn(
         "beem1",
         [x[0] for x in op[role]["account_auths"]])
     self.assertEqual(
         op["creator"],
         "beem")
Beispiel #16
0
def checkkey(username, password, role):
    listOfValidRoles = ['owner' , 'active', 'posting', 'memo']
    if role not in listOfValidRoles:
        print(role + " NOT found in List : " , listOfValidRoles)
        sys.exit("Wrong role " + role)

    try:
        account = Account(username, steem_instance=stmf)
    except:
        sys.exit("Wrong username " + username)

    try:
        publickey = str(PrivateKey(password, prefix="EUR").pubkey)
    except:
        sys.exit("Wrong password syntax " + password)

    blk_auths_public = {}
    if role == "memo": 
        blk_auths_public[role] = str(account.json()["memo_key"])
    else:
        blk_auths_public[role] = str(account.json()[role]["key_auths"][0][0])

    if publickey == blk_auths_public[role]:
        return True
    else:
        return False
Beispiel #17
0
    def __init__(
        self,
        from_account=None,
        to_account=None,
        blockchain_instance=None,
        **kwargs
    ):
        if blockchain_instance is None:
            if kwargs.get("steem_instance"):
                blockchain_instance = kwargs["steem_instance"]
            elif kwargs.get("hive_instance"):
                blockchain_instance = kwargs["hive_instance"]
        self.blockchain = blockchain_instance or shared_blockchain_instance()

        if to_account and len(to_account) < 51:
            self.to_account = Account(to_account, blockchain_instance=self.blockchain)
        elif to_account and len(to_account) >= 51:
            self.to_account = PublicKey(to_account)
        else:
            self.to_account = None
        if from_account and len(from_account) < 51:
            self.from_account = Account(from_account, blockchain_instance=self.blockchain)
        elif from_account and len(from_account) >= 51:
            self.from_account = PrivateKey(from_account)
        else:
            self.from_account = None
Beispiel #18
0
 def encrypt_wif(self, wif):
     """ Encrypt a wif key
     """
     if self.locked():
         raise AssertionError()
     return format(
         bip38.encrypt(PrivateKey(wif, prefix=self.prefix), self.masterpassword), "encwif")
Beispiel #19
0
    def encrypt_binary(self, infile, outfile, buffer_size=2048, nonce=None):
        """ Encrypt a binary file

            :param str infile: input file name
            :param str outfile: output file name
            :param int buffer_size: write buffer size
            :param str nonce: when not set, a random string is generated and used
        """
        if not os.path.exists(infile):
            raise ValueError("%s does not exists!" % infile)

        if nonce is None:
            nonce = str(random.getrandbits(64))
        if isinstance(self.from_account, Account):
            memo_wif = self.blockchain.wallet.getPrivateKeyForPublicKey(
                self.from_account["memo_key"]
            )
        else:
            memo_wif = self.from_account
        if isinstance(self.to_account, Account):
            pubkey = self.to_account["memo_key"]
        else:
            pubkey = self.to_account        
        if not memo_wif:
            raise MissingKeyError("Memo key for %s missing!" % self.from_account["name"])

        if not hasattr(self, 'chain_prefix'):
            self.chain_prefix = self.blockchain.prefix

        file_size = os.path.getsize(infile)
        priv = PrivateKey(memo_wif)
        pub = PublicKey(
                pubkey,
                prefix=self.chain_prefix
            )
        enc = BtsMemo.encode_memo(
            priv,
            pub,
            nonce,
            "beem/%s" % __version__,
            prefix=self.chain_prefix
        )
        enc = unhexlify(base58decode(enc[1:]))
        shared_secret = BtsMemo.get_shared_secret(priv, pub)
        aes, check = BtsMemo.init_aes(shared_secret, nonce)
        with open(outfile, 'wb') as fout:
            fout.write(struct.pack('<Q', len(enc)))
            fout.write(enc)
            fout.write(struct.pack('<Q', file_size))
            with open(infile, 'rb') as fin:
                while True:
                    data = fin.read(buffer_size)
                    n = len(data)
                    if n == 0:
                        break
                    elif n % 16 != 0:
                        data += b' ' * (16 - n % 16) # <- padded with spaces
                    encd = aes.encrypt(data)
                    fout.write(encd)
Beispiel #20
0
 def test_encrypt(self):
     for memo in test_cases:
         enc = encode_memo(PrivateKey(memo["wif"]),
                           PublicKey(memo["to"], prefix="GPH"),
                           memo["nonce"],
                           memo["plain"],
                           prefix="GPH")
         self.assertEqual(memo["message"], enc)
Beispiel #21
0
 def test_create_account_password(self):
     bts = Hive(node=get_hive_nodes(),
                 nobroadcast=True,
                 unsigned=True,
                 data_refresh_time_seconds=900,
                 keys={"active": wif, "owner": wif2, "memo": wif3},
                 num_retries=10)
     core_unit = "STM"
     name = ''.join(random.choice(string.ascii_lowercase) for _ in range(12))
     key5 = PrivateKey()
     bts.txbuffer.clear()
     tx = bts.create_account(
         name,
         creator="test",   # 1.2.7
         password="******",
         additional_owner_keys=[format(key5.pubkey, core_unit)],
         additional_active_keys=[format(key5.pubkey, core_unit)],
         additional_posting_keys=[format(key5.pubkey, core_unit)],
         additional_owner_accounts=["test1"],  # 1.2.0
         additional_active_accounts=["test1"],
         storekeys=False,
     )
     if isinstance(tx["operations"][0], list):
         self.assertEqual(
             tx["operations"][0][0],
             "account_create"
         )
         op = tx["operations"][0][1]
     else:
         self.assertEqual(
             tx["operations"][0]["type"],
             "account_create_operation"
         )
         op = tx["operations"][0]["value"]        
     role = "active"
     self.assertIn(
         format(key5.pubkey, core_unit),
         [x[0] for x in op[role]["key_auths"]])
     self.assertIn(
         format(key5.pubkey, core_unit),
         [x[0] for x in op[role]["key_auths"]])
     self.assertIn(
         "test1",
         [x[0] for x in op[role]["account_auths"]])
     role = "owner"
     self.assertIn(
         format(key5.pubkey, core_unit),
         [x[0] for x in op[role]["key_auths"]])
     self.assertIn(
         format(key5.pubkey, core_unit),
         [x[0] for x in op[role]["key_auths"]])
     self.assertIn(
         "test1",
         [x[0] for x in op[role]["account_auths"]])
     self.assertEqual(
         op["creator"],
         "test")
Beispiel #22
0
 def test_decrypt_bugged_padding_bts(self):
     for memo in not_enough_padding:
         dec = decode_memo_bts(
             PrivateKey(memo["wif"]),
             PublicKey(memo["to"], prefix="GPH"),
             memo["nonce"],
             memo["message_bts"],
         )
         self.assertEqual(memo["plain"], dec)
Beispiel #23
0
 def test_decrypt_bts(self):
     for memo in test_cases:
         dec = decode_memo_bts(
             PrivateKey(memo["wif"]),
             PublicKey(memo["to"], prefix="GPH"),
             memo["nonce"],
             memo["message_bts"],
         )
         self.assertEqual(memo["plain"], dec)
 def doit(self, printWire=False, ops=None):
     if ops is None:
         ops = [Operation(self.op)]
     tx = Signed_Transaction(ref_block_num=self.ref_block_num,
                             ref_block_prefix=self.ref_block_prefix,
                             expiration=self.expiration,
                             operations=ops)
     tx = tx.sign([self.wif], chain=self.prefix)
     tx.verify([PrivateKey(self.wif, prefix=u"STM").pubkey], self.prefix)
     txWire = hexlify(py23_bytes(tx)).decode("ascii")
Beispiel #25
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
Beispiel #26
0
 def test_create_account_password(self, node_param):
     if node_param == "non_appbase":
         bts = Steem(node=self.nodelist.get_nodes(appbase=False),
                     nobroadcast=True,
                     unsigned=True,
                     data_refresh_time_seconds=900,
                     keys={
                         "active": wif,
                         "owner": wif,
                         "memo": wif
                     },
                     num_retries=10)
     elif node_param == "appbase":
         bts = Steem(node=self.nodelist.get_nodes(normal=False,
                                                  appbase=True),
                     nobroadcast=True,
                     unsigned=True,
                     data_refresh_time_seconds=900,
                     keys={
                         "active": wif,
                         "owner": wif,
                         "memo": wif
                     },
                     num_retries=10)
     name = ''.join(
         random.choice(string.ascii_lowercase) for _ in range(12))
     key5 = PrivateKey()
     bts.txbuffer.clear()
     tx = bts.create_account(
         name,
         creator="test",  # 1.2.7
         password="******",
         additional_owner_keys=[format(key5.pubkey, core_unit)],
         additional_active_keys=[format(key5.pubkey, core_unit)],
         additional_posting_keys=[format(key5.pubkey, core_unit)],
         additional_owner_accounts=["test1"],  # 1.2.0
         additional_active_accounts=["test1"],
         storekeys=False,
         delegation_fee_steem="0 STEEM")
     self.assertEqual(tx["operations"][0][0], "account_create")
     op = tx["operations"][0][1]
     role = "active"
     self.assertIn(format(key5.pubkey, core_unit),
                   [x[0] for x in op[role]["key_auths"]])
     self.assertIn(format(key5.pubkey, core_unit),
                   [x[0] for x in op[role]["key_auths"]])
     self.assertIn("test1", [x[0] for x in op[role]["account_auths"]])
     role = "owner"
     self.assertIn(format(key5.pubkey, core_unit),
                   [x[0] for x in op[role]["key_auths"]])
     self.assertIn(format(key5.pubkey, core_unit),
                   [x[0] for x in op[role]["key_auths"]])
     self.assertIn("test1", [x[0] for x in op[role]["account_auths"]])
     self.assertEqual(op["creator"], "test")
Beispiel #27
0
    def appendWif(self, wif):
        """ Add a wif that should be used for signing of the transaction.

            :param string wif: One wif key to use for signing
                a transaction.
        """
        if wif:
            try:
                PrivateKey(wif, prefix=self.steem.prefix)
                self.wifs.add(wif)
            except:
                raise InvalidWifError
Beispiel #28
0
 def _get_pub_from_wif(self, wif):
     """ Get the pubkey as string, from the wif key as string
     """
     # it could be either graphenebase or steem so we can't check
     # the type directly
     if isinstance(wif, PrivateKey):
         wif = str(wif)
     try:
         return format(PrivateKey(wif).pubkey, self.prefix)
     except:
         raise InvalidWifError(
             "Invalid Private Key Format. Please use WIF!")
Beispiel #29
0
 def decrypt_wif(self, encwif):
     """ decrypt a wif key
     """
     try:
         # Try to decode as wif
         PrivateKey(encwif, prefix=self.prefix)
         return encwif
     except (ValueError, AssertionError):
         pass
     if self.locked():
         raise AssertionError()
     return format(bip38.decrypt(encwif, self.masterpassword), "wif")
 def doit(self, printWire=False, ops=None):
     ops = [Operation(ops)]
     tx = Signed_Transaction(ref_block_num=self.ref_block_num,
                             ref_block_prefix=self.ref_block_prefix,
                             expiration=self.expiration,
                             operations=ops)
     start = timer()
     tx = tx.sign([self.wif], chain=self.prefix)
     end1 = timer()
     tx.verify([PrivateKey(self.wif, prefix=u"STM").pubkey], self.prefix)
     end2 = timer()
     return end2 - end1, end1 - start