Beispiel #1
0
 def test_encrypt(self):
     self.assertEqual(
         [
             format(
                 encrypt(
                     PrivateKey(
                         "5HqUkGuo62BfcJU5vNhTXKJRXuUi9QSE6jp8C3uBJ2BVHtB8WSd"
                     ), "TestingOneTwoThree"),
                 "encwif",
             ),
             format(
                 encrypt(
                     PrivateKey(
                         "5KN7MzqK5wt2TP1fQCYyHBtDrXdJuXbUzm4A9rKAteGu3Qi5CVR"
                     ), "TestingOneTwoThree"),
                 "encwif",
             ),
             format(
                 encrypt(
                     PrivateKey(
                         "5HtasZ6ofTHP6HCwTqTkLDuLQisYPah7aUnSKfC7h4hMUVw2gi5"
                     ), "Satoshi"), "encwif"),
         ],
         [
             "6PRN5mjUTtud6fUXbJXezfn6oABoSr6GSLjMbrGXRZxSUcxThxsUW8epQi",
             "6PRVWUbkzzsbcVac2qwfssoUJAN1Xhrg6bNk8J7Nzm5H7kxEbn2Nh2ZoGg",
             "6PRNFFkZc2NZ6dJqFfhRoFNMR9Lnyj7dYGrzdgXXVMXcxoKTePPX1dWByq",
         ],
     )
 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_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 #4
0
    def test_memo(self):
        from_priv = "5KNK3bejeP3PtQ1Q9EagBmGacYFCZ3qigRAZDbfqcdjDWWmZSMm"
        to_priv = "5K2JRPe1iRwD2He5DyDRtHs3Z1wpom3YXguFxEd57kNTHhQuZ2k"

        for msg in [
                "foobar",
                "just a donation",
                "1124safafASFasc",
        ]:
            nonce = random.getrandbits(64)
            memo = Memo.encode_memo(PrivateKey(from_priv),
                                    PrivateKey(to_priv).pubkey, nonce, msg)
            plain = Memo.decode_memo(PrivateKey(to_priv), memo)
            self.assertEqual(msg, plain)
Beispiel #5
0
 def appendWif(self, wif):
     if wif:
         try:
             PrivateKey(wif)
             self.wifs.append(wif)
         except:
             raise InvalidKeyFormat
Beispiel #6
0
    def test_Vote(self):
        op = operations.Vote(
            **{"voter": "foobara",
               "author": "foobarc",
               "permlink": "foobard",
               "weight": 1000}
        )
        ops = [operations.Operation(op)]
        tx = SignedTransaction(
            ref_block_num=ref_block_num,
            ref_block_prefix=ref_block_prefix,
            expiration=expiration,
            operations=ops
        )
        tx = tx.sign([wif], chain=self.steem.chain_params)

        tx.verify([PrivateKey(wif).pubkey], chain=self.steem.chain_params)

        tx_wire = hexlify(bytes(tx)).decode("ascii")

        compare = ("f68585abf4dce7c80457010007666f6f6261726107666f6f62617263"
                   "07666f6f62617264e8030001202e09123f732a438ef6d6138484d7ad"
                   "edfdcf4a4f3d171f7fcafe836efa2a3c8877290bd34c67eded824ac0"
                   "cc39e33d154d0617f64af936a83c442f62aef08fec")
        self.assertEqual(compare[:-130], tx_wire[:-130])
def main(ctx):
    """Generate random keypair."""

    wif = PrivateKey()
    prefix = ctx.helper.steemd.chain_params["prefix"]
    pubkey = format(wif.pubkey, prefix)

    print(f'private key: {str(wif)}')
    print(f'public key: {pubkey}')
Beispiel #8
0
 def decrypt_wif(self, encwif):
     """decrypt a wif key."""
     try:
         # Try to decode as wif
         PrivateKey(encwif)
         return encwif
     except:
         pass
     self.unlock()
     return format(bip38.decrypt(encwif, self.masterpassword), "wif")
 def test_Privatekey(self):
     self.assertEqual([
         str(
             PrivateKey(
                 "5HvVz6XMx84aC5KaaBbwYrRLvWE46cH6zVnv4827SBPLorg76oq")),
         str(
             PrivateKey(
                 "5Jete5oFNjjk3aUMkKuxgAXsp7ZyhgJbYNiNjHLvq5xzXkiqw7R")),
         str(
             PrivateKey(
                 "5KDT58ksNsVKjYShG4Ls5ZtredybSxzmKec8juj7CojZj6LPRF7")),
         repr(
             PrivateKey(
                 "5HvVz6XMx84aC5KaaBbwYrRLvWE46cH6zVnv4827SBPLorg76oq")),
         repr(
             PrivateKey(
                 "5Jete5oFNjjk3aUMkKuxgAXsp7ZyhgJbYNiNjHLvq5xzXkiqw7R")),
         repr(
             PrivateKey(
                 "5KDT58ksNsVKjYShG4Ls5ZtredybSxzmKec8juj7CojZj6LPRF7")),
     ], [
         "5HvVz6XMx84aC5KaaBbwYrRLvWE46cH6zVnv4827SBPLorg76oq",
         "5Jete5oFNjjk3aUMkKuxgAXsp7ZyhgJbYNiNjHLvq5xzXkiqw7R",
         "5KDT58ksNsVKjYShG4Ls5ZtredybSxzmKec8juj7CojZj6LPRF7",
         '0e1bfc9024d1f55a7855dc690e45b2e089d2d825a4671a3c3c7e4ea4e74ec00e',
         '6e5cc4653d46e690c709ed9e0570a2c75a286ad7c1bc69a648aae6855d919d3e',
         'b84abd64d66ee1dd614230ebbe9d9c6d66d78d93927c395196666762e9ad69d8'
     ])
def main():

    parser = argparse.ArgumentParser(
        description='This script is for generating a keypair.',
        epilog='Report bugs to: https://github.com/bitfag/golos-scripts/issues'
    )
    parser.add_argument('-d',
                        '--debug',
                        action='store_true',
                        help='enable debug output'),
    parser.add_argument('-c',
                        '--config',
                        default='./common.yml',
                        help='specify custom path for config file')
    args = parser.parse_args()

    # create logger
    if args.debug == True:
        log.setLevel(logging.DEBUG)
    else:
        log.setLevel(logging.INFO)
    handler = logging.StreamHandler()
    formatter = logging.Formatter("%(asctime)s %(levelname)s: %(message)s")
    handler.setFormatter(formatter)
    log.addHandler(handler)

    # parse config
    with open(args.config, 'r') as ymlfile:
        conf = yaml.load(ymlfile)

    golos = Steem(nodes=conf['nodes_old'],
                  no_broadcast=False,
                  keys=conf['keys'])

    password = functions.generate_password()

    a = bytes(password, 'utf8')
    s = hashlib.sha256(a).digest()

    privkey = PrivateKey(hexlify(s).decode('ascii'))
    print('private: {}'.format(
        str(privkey)))  # we need explicit str() conversion!

    # pubkey with correct prefix
    key = format(privkey.pubkey, golos.chain_params["prefix"])
    print('public: {}'.format(key))
Beispiel #11
0
    def addPrivateKey(self, wif):
        """ Add a private key to the wallet database
        """
        # it could be either graphenebase or pistonbase so we can't check the type directly
        if isinstance(wif, PrivateKey) or isinstance(wif, PrivateKey):
            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():
                self.newWallet()
            self.keyStorage.add(self.encrypt_wif(wif), pub)
Beispiel #12
0
    def setKeys(self, loadkeys):
        """This method is strictly only for in memory keys that are passed to Wallet/Steem 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)
Beispiel #13
0
def decrypt(encrypted_privkey, passphrase):
    """BIP0038 non-ec-multiply decryption. Returns WIF privkey.

    :param Base58 encrypted_privkey: Private key
    :param str passphrase: UTF-8 encoded passphrase for decryption
    :return: BIP0038 non-ec-multiply decrypted key
    :rtype: Base58
    :raises SaltException: if checksum verification failed (e.g. wrong password)

    """

    d = unhexlify(base58decode(encrypted_privkey))
    d = d[2:]  # remove trailing 0x01 and 0x42
    flagbyte = d[0:1]  # get flag byte
    d = d[1:]  # get payload
    assert flagbyte == b'\xc0', "Flagbyte has to be 0xc0"
    salt = d[0:4]
    d = d[4:-4]
    if SCRYPT_MODULE == "scrypt":
        key = scrypt.hash(passphrase, salt, 16384, 8, 8)
    elif SCRYPT_MODULE == "pylibscrypt":
        key = scrypt.scrypt(bytes(passphrase, "utf-8"), salt, 16384, 8, 8)
    else:
        raise ValueError("No scrypt module loaded")
    derivedhalf1 = key[0:32]
    derivedhalf2 = key[32:64]
    encryptedhalf1 = d[0:16]
    encryptedhalf2 = d[16:32]
    aes = AES.new(derivedhalf2)
    decryptedhalf2 = aes.decrypt(encryptedhalf2)
    decryptedhalf1 = aes.decrypt(encryptedhalf1)
    privraw = decryptedhalf1 + decryptedhalf2
    privraw = ('%064x' %
               (int(hexlify(privraw), 16) ^ int(hexlify(derivedhalf1), 16)))
    wif = Base58(privraw)
    """ Verify Salt """
    privkey = PrivateKey(format(wif, "wif"))
    addr = format(privkey.uncompressed.address, "BTC")
    a = bytes(addr, 'ascii')
    saltverify = hashlib.sha256(hashlib.sha256(a).digest()).digest()[0:4]
    if saltverify != salt:
        raise SaltException('checksum verification failed! Password may be incorrect.')
    return wif
Beispiel #14
0
    def sign(self, wifkeys, chain=None):
        """ Sign the transaction with the provided private keys.

            :param list wifkeys: Array of wif keys
            :param str chain: identifier for the chain

        """
        if not chain:
            raise ValueError("Chain needs to be provided!")
        self.deriveDigest(chain)

        # Get Unique private keys
        self.privkeys = []
        [
            self.privkeys.append(item) for item in wifkeys
            if item not in self.privkeys
        ]

        # Sign the message with every private key given!
        sigs = []
        for wif in self.privkeys:
            p = bytes(PrivateKey(wif))
            i = 0
            if USE_SECP256K1:
                ndata = secp256k1.ffi.new("const int *ndata")
                ndata[0] = 0
                while True:
                    ndata[0] += 1
                    privkey = secp256k1.PrivateKey(p, raw=True)
                    sig = secp256k1.ffi.new(
                        'secp256k1_ecdsa_recoverable_signature *')
                    signed = secp256k1.lib.secp256k1_ecdsa_sign_recoverable(
                        privkey.ctx, sig, self.digest, privkey.private_key,
                        secp256k1.ffi.NULL, ndata)
                    assert signed == 1
                    signature, i = privkey.ecdsa_recoverable_serialize(sig)
                    if self._is_canonical(signature):
                        i += 4  # compressed
                        i += 27  # compact
                        break
            else:
                cnt = 0
                sk = ecdsa.SigningKey.from_string(p, curve=ecdsa.SECP256k1)
                while 1:
                    cnt += 1
                    if not cnt % 20:
                        log.info(
                            "Still searching for a canonical signature. Tried %d times already!"
                            % cnt)

                    # Deterministic k
                    #
                    k = ecdsa.rfc6979.generate_k(
                        sk.curve.generator.order(),
                        sk.privkey.secret_multiplier,
                        hashlib.sha256,
                        hashlib.sha256(
                            self.digest + struct.pack("d", time.time(
                            ))  # use the local time to randomize the signature
                        ).digest())

                    # Sign message
                    #
                    sigder = sk.sign_digest(self.digest,
                                            sigencode=ecdsa.util.sigencode_der,
                                            k=k)

                    # Reformating of signature
                    #
                    r, s = ecdsa.util.sigdecode_der(sigder,
                                                    sk.curve.generator.order())
                    signature = ecdsa.util.sigencode_string(
                        r, s, sk.curve.generator.order())

                    # Make sure signature is canonical!
                    #
                    lenR = sigder[3]
                    lenS = sigder[5 + lenR]
                    if lenR is 32 and lenS is 32:
                        # Derive the recovery parameter
                        #
                        i = self.recoverPubkeyParameter(
                            self.digest, signature, sk.get_verifying_key())
                        i += 4  # compressed
                        i += 27  # compact
                        break

            # pack signature
            #
            sigstr = struct.pack("<B", i)
            sigstr += signature

            sigs.append(Signature(sigstr))

        self.data["signatures"] = Array(sigs)
        return self
Beispiel #15
0
 def getAccountFromPrivateKey(self, wif):
     """ Obtain account name from private key
     """
     pub = format(PrivateKey(wif).pubkey, self.prefix)
     return self.getAccountFromPublicKey(pub)
Beispiel #16
0
 def encrypt_wif(self, wif):
     """ Encrypt a wif key
     """
     self.unlock()
     return format(bip38.encrypt(PrivateKey(wif), self.masterpassword),
                   "encwif")