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()
     tx = bts.create_account(
         name,
         registrar="init0",   # 1.2.7
         referrer="init1",    # 1.2.8
         referrer_percent=33,
         owner_key=format(key1.pubkey, core_unit),
         active_key=format(key2.pubkey, core_unit),
         memo_key=format(key3.pubkey, core_unit),
         additional_owner_keys=[format(key4.pubkey, core_unit)],
         additional_active_keys=[format(key4.pubkey, core_unit)],
         additional_owner_accounts=["committee-account"],  # 1.2.0
         additional_active_accounts=["committee-account"],
         proxy_account="init0",
         storekeys=False
     )
     self.assertEqual(
         getOperationNameForId(tx["operations"][0][0]),
         "account_create"
     )
     op = tx["operations"][0][1]
     role = "active"
     self.assertIn(
         format(key4.pubkey, core_unit),
         [x[0] for x in op[role]["key_auths"]])
     self.assertIn(
         format(key4.pubkey, core_unit),
         [x[0] for x in op[role]["key_auths"]])
     self.assertIn(
         "1.2.0",
         [x[0] for x in op[role]["account_auths"]])
     role = "owner"
     self.assertIn(
         format(key4.pubkey, core_unit),
         [x[0] for x in op[role]["key_auths"]])
     self.assertIn(
         format(key4.pubkey, core_unit),
         [x[0] for x in op[role]["key_auths"]])
     self.assertIn(
         "1.2.0",
         [x[0] for x in op[role]["account_auths"]])
     self.assertEqual(
         op["options"]["voting_account"],
         "1.2.6")
     self.assertEqual(
         op["registrar"],
         "1.2.6")
     self.assertEqual(
         op["referrer"],
         "1.2.7")
     self.assertEqual(
         op["referrer_percent"],
         33 * 100)
 def test_encrypt(self):
     for memo in test_cases:
         enc = encode_memo(PrivateKey(memo["wif"]),
                           PublicKey(memo["to"], prefix="GPH"),
                           memo["nonce"],
                           memo["plain"])
         self.assertEqual(memo["message"], enc)
Exemple #3
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
        try:
            memo_wif = self.transnet.wallet.getPrivateKeyForPublicKey(
                memo["to"])
            pubkey = memo["from"]
        except KeyNotFound:
            try:
                # if that failed, we assume that we have sent the memo
                memo_wif = self.transnet.wallet.getPrivateKeyForPublicKey(
                    memo["from"])
                pubkey = memo["to"]
            except KeyNotFound:
                # if all fails, raise exception
                raise MissingKeyError(
                    "Non of the required memo keys are installed!"
                    "Need any of {}".format([memo["to"], memo["from"]]))

        return TrnsMemo.decode_memo(
            PrivateKey(memo_wif), PublicKey(pubkey,
                                            prefix=self.transnet.prefix),
            memo.get("nonce"), memo.get("message"))
Exemple #4
0
    def encrypt(self, memo):
        """ 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.transnet.wallet.getPrivateKeyForPublicKey(
            self.from_account["options"]["memo_key"])
        if not memo_wif:
            raise MissingKeyError("Memo key for %s missing!" %
                                  self.from_account["name"])

        enc = TrnsMemo.encode_memo(
            PrivateKey(memo_wif),
            PublicKey(self.to_account["options"]["memo_key"],
                      prefix=self.transnet.prefix), nonce, memo)

        return {
            "message": enc,
            "nonce": nonce,
            "from": self.from_account["options"]["memo_key"],
            "to": self.to_account["options"]["memo_key"]
        }
    def compareConstructedTX(self):
        self.maxDiff = None
        self.op = operations.Bid_collateral(**{
            'fee': {'amount': 100,
                    'asset_id': '1.3.0'},
            'additional_collateral': {
                'amount': 10000,
                'asset_id': '1.3.22'},
            'debt_covered': {
                'amount': 100000000,
                'asset_id': '1.3.0'},
            'bidder': '1.2.29',
            'extensions': []
        })
        ops = [Operation(self.op)]
        tx = Signed_Transaction(
            ref_block_num=ref_block_num,
            ref_block_prefix=ref_block_prefix,
            expiration=expiration,
            operations=ops
        )
        tx = tx.sign([wif], chain=prefix)
        tx.verify([PrivateKey(wif).pubkey], prefix)
        txWire = hexlify(bytes(tx)).decode("ascii")
        print("=" * 80)
        pprint(tx.json())
        print("=" * 80)

        from grapheneapi.grapheneapi import GrapheneAPI
        rpc = GrapheneAPI("localhost", 8092)
        self.cm = rpc.serialize_transaction(tx.json())
        print("soll: %s" % self.cm[:-130])
        print("ist:  %s" % txWire[:-130])
        print(txWire[:-130] == self.cm[:-130])
        self.assertEqual(self.cm[:-130], txWire[:-130])
 def appendWif(self, wif):
     """ Add a wif that should be used for signing of the transaction.
     """
     if wif:
         try:
             PrivateKey(wif)
             self.wifs.add(wif)
         except:
             raise InvalidWifError
Exemple #7
0
 def decrypt_wif(self, encwif):
     """ decrypt a wif key
     """
     try:
         # Try to decode as wif
         PrivateKey(encwif)
         return encwif
     except:
         pass
     assert not self.locked()
     return format(bip38.decrypt(encwif, self.masterpassword), "wif")
Exemple #8
0
    def setKeys(self, loadkeys):
        """ This method is strictly only for in memory keys that are
            passed to Wallet/Transnet with the ``keys`` argument
        """
        log.debug(
            "Force setting of private keys. Not using the wallet database!")
        if isinstance(loadkeys, dict):
            Wallet.keyMap = loadkeys
            loadkeys = list(loadkeys.values())
        elif not isinstance(loadkeys, list):
            loadkeys = [loadkeys]

        for wif in loadkeys:
            try:
                key = PrivateKey(wif)
            except:
                raise InvalidWifError
            Wallet.keys[format(key.pubkey, self.prefix)] = str(key)
Exemple #9
0
    def addPrivateKey(self, wif):
        """ Add a private key to the wallet database
        """
        # it could be either graphenebase or peerplaysbase so we can't check
        # the type directly
        if isinstance(wif, PrivateKey) or isinstance(wif, GPHPrivateKey):
            wif = str(wif)
        try:
            pub = format(PrivateKey(wif).pubkey, self.prefix)
        except:
            raise InvalidWifError(
                "Invalid Private Key Format. Please use WIF!")

        if self.keyStorage:
            # Test if wallet exists
            if not self.created():
                raise NoWalletException
            self.keyStorage.add(self.encrypt_wif(wif), pub)
    def doit(self, printWire=False):
        ops = [Operation(self.op)]
        tx = Signed_Transaction(ref_block_num=ref_block_num,
                                ref_block_prefix=ref_block_prefix,
                                expiration=expiration,
                                operations=ops)
        tx = tx.sign([wif], chain=prefix)
        tx.verify([PrivateKey(wif).pubkey], prefix)
        txWire = hexlify(bytes(tx)).decode("ascii")
        if printWire:
            print()
            print(txWire)
            print()
        self.assertEqual(self.cm[:-130], txWire[:-130])

        if TEST_AGAINST_CLI_WALLET:
            from grapheneapi.grapheneapi import GrapheneAPI
            rpc = GrapheneAPI("localhost", 8092)
            self.cm = rpc.serialize_transaction(tx.json())
            # print("soll: %s" % self.cm[:-130])
            # print("ist:  %s" % txWire[:-130])
            # print(txWire[:-130] == self.cm[:-130])
            self.assertEqual(self.cm[:-130], txWire[:-130])
 def test_shared_secret(self):
     for s in test_shared_secrets:
         priv = PrivateKey(s[0])
         pub = PublicKey(s[1], prefix="GPH")
         shared_secret = get_shared_secret(priv, pub)
         self.assertEqual(s[2], shared_secret)
Exemple #12
0
 def getAccountFromPrivateKey(self, wif):
     """ Obtain account name from private key
     """
     pub = format(PrivateKey(wif).pubkey, self.prefix)
     return self.getAccountFromPublicKey(pub)
Exemple #13
0
 def encrypt_wif(self, wif):
     """ Encrypt a wif key
     """
     assert not self.locked()
     return format(bip38.encrypt(PrivateKey(wif), self.masterpassword),
                   "encwif")