def stealth_generate(filename):
    #Check to see if file is valid and does not already exist
    if type(filename) != str or len(filename) == 0:
        print("Stealth Address Generation Failed!")
        print("Please enter valid filename!")
        return

    if os.path.exists(filename):
        print("Stealth Address Generation Failed!")
        print("File \"" + filename + "\" already exists!")
        return

    #Get password for new keypair
    password = getpass()

    #Generate private keys
    print("Generating stealth address key pair...", end="")
    rng = SystemRandom()

    scan_key = (rng.getrandbits(256) % secp256k1.N).to_bytes(32, "big")
    pub_scan_key = secp256k1.privtopub(scan_key)
    js_scan = create_keyfile_json(scan_key, bytes(password, 'utf'))
    del scan_key

    spend_key = (rng.getrandbits(256) % secp256k1.N).to_bytes(32, "big")
    pub_spend_key = secp256k1.privtopub(spend_key)
    js_spend = create_keyfile_json(spend_key, bytes(password, 'utf'))
    del spend_key
    del password

    #Calculate Stealth Address and write to file with key pairs
    stealth_address = int.from_bytes(
        GetStealthAddressFromKeys(pub_scan_key, pub_spend_key), 'big')
    print("DONE!")
    print("New Stealth Address: " + hex(stealth_address))

    print("Writing keystore file \"" + filename + "\"...", end="")

    with open(filename, mode='w') as file:
        js = "{\"stealth_address\":\"" + hex(stealth_address) + "\","
        js += "\"scan_key\":"
        file.write(js)

        json.dump(js_scan, file)

        js = ",\"spend_key\":"
        file.write(js)

        json.dump(js_spend, file)

        js = "}"
        file.write(js)

    print("Done!")
Exemple #2
0
def stealth_receive(directory):
    #Import Scan and Spend Key
    wallet = GetKeysFromFile(directory + 'wallet.json')
    scan_key = wallet['scan_key']
    spend_key = wallet['spend_key']
    del wallet

    pub_scan_key = secp256k1.privtopub(scan_key)
    pub_spend_key = secp256k1.privtopub(spend_key)
    stealth_address = GetStealthAddressFromKeys(pub_scan_key, pub_spend_key)

    print("Stealth Address Imported: " + hex(int.from_bytes(stealth_address, 'big')))

    #Import Inputs File
    input_json = json.load(open(directory + "input.json"))
    print()
    print("Input Count: " + str(len(input_json["keys"])))

    for key in input_json["keys"]:
        #Extract and pad address and key fields
        addr = key["address"][2:]
        while len(addr) < 40:
            addr = "0" + addr
        addr = bytes.fromhex(addr)
        
        key = key["key"][2:]
        while len(key) < 66:
            key = "0" + key
        key = bytes.fromhex(key)

        print("Testing " + hex(int.from_bytes(addr, 'big')) + " ... ", end="")
        point = ExpandPoint(key)

        ss = GetSharedSecret(point, scan_key)
        addr_exp = GetAddrFromSharedSecret(ss, pub_spend_key)

        if addr == addr_exp:
            print("HIT!")
            priv_key = GetPrivKeyFromSharedSecret(ss, spend_key)
            filename = "Keystore--" + hex(int.from_bytes(addr_exp, 'big'))[2:] + ".json"
            
            print("Creating " + filename + " ... ", end="")
            filename = directory + filename
            
            with open(filename, mode='w') as file:
                js = create_keyfile_json(int.to_bytes(priv_key, 32, 'big'), bytes(password, 'utf'))
                json.dump(js, file)

            print("COMPLETE!")
        else:
            print("MISS!")

    del scan_key
    del spend_key
Exemple #3
0
def priv_to_addr(k):
    k = normalize_key(k)
    x, y = privtopub(k)
    addr = bytearray(sha3(encode_int32(x) + encode_int32(y))[12:])
    addr[0] &= 0x0f
    addr[0] |= 0x10
    return bytes(addr)
Exemple #4
0
def get_pubkey(privkey):
    """Derives a public key from a private one.
    
    Args:
        privkey (int|bytes): the private key to derive the public one from.
        
    Returns:
        bytes: the corresponding public key 
    """
    # Checking key format
    if isinstance(privkey, int):
        privkey = privkey.to_bytes(sizeof(privkey), 'big')
    elif not isinstance(privkey, bytes):
        raise ValueError("Private key must be passed as int or bytes")
    # Checking key compression
    compressed = len(privkey) == 33
    if compressed:
        privkey = privkey[:32]
    # Derivating key points
    (x, y) = secp256k1.privtopub(privkey)
    # Returning key in corresponding format
    if not compressed:
        pk = 0x04.to_bytes(1, 'big') + x.to_bytes(sizeof(x), 'big') + y.to_bytes(sizeof(y), 'big')
    else:
        if y%2: # y is odd, so point is greater than the midpoint
            pk = 0x03.to_bytes(1, 'big') + x.to_bytes(sizeof(x), 'big')
        else: # point is less than the midpoint
            pk = 0x02.to_bytes(1, 'big') + x.to_bytes(sizeof(x), 'big')
    return pk # type : bytes
Exemple #5
0
    def prestart(self):
        super().prestart()

        # geth is locked to user home
        home = os.path.expanduser("~")
        dagfile = os.path.join(home, '.ethash', 'full-R23-0000000000000000')
        if not os.path.exists(dagfile):
            raise Exception("Missing DAG {}. run {} makedag 0 {} to initialise ethminer before tests can be run".format(
                dagfile, self.geth_server, os.path.join(home, '.ethash')))

        if self.settings['rpcport'] is None:
            self.settings['rpcport'] = get_unused_port()

        if self.settings['node_key'] is None:
            self.settings['node_key'] = "{:0>64}".format(binascii.b2a_hex(os.urandom(32)).decode('ascii'))

        if self.settings['ws'] is not None:
            self.settings['wsport'] = get_unused_port()

        pub_x, pub_y = privtopub(binascii.a2b_hex(self.settings['node_key']))
        pub = encode_int32(pub_x) + encode_int32(pub_y)
        self.public_key = "{:0>128}".format(binascii.b2a_hex(pub).decode('ascii'))

        # write chain file
        write_chain_file(self.version, self.chainfile, self.author, self.difficulty)

        p = subprocess.Popen([self.geth_server, '--datadir', self.get_data_directory(), 'init', self.chainfile], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        outs, errs = p.communicate(timeout=15)

        with open(os.path.join(self.get_data_directory(), 'keystore', 'UTC--2017-02-06T16-16-34.720321115Z--de3d2d9dd52ea80f7799ef4791063a5458d13913'), 'w') as inf:
            inf.write('''{"address":"de3d2d9dd52ea80f7799ef4791063a5458d13913","crypto":{"cipher":"aes-128-ctr","ciphertext":"8d6528acfb366722d9c98f64435bb151f5671f9e4623e546cc7206382a1d54f7","cipherparams":{"iv":"de95c854face9aa50686370cc47d6025"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"6baa74518f9cc34575c981e027154e9c714b400710478c587043c900a37a89b8"},"mac":"37b6d35ea394b129f07e9a90a09b8cc1356d731590201e84405f4592013b4333"},"id":"ce658bd4-6910-4eef-aa39-b32000c38ccc","version":3}''')
Exemple #6
0
def get_pubkey_points(privkey):
    """Derives a public key from a private one.
    
    Args:
        privkey (int|bytes): the private key to derive the public one from.
        
    Returns:
        tuple: the points (x, y) of the public key on the secp256k1 curve 
    """
    if isinstance(privkey, int):
        if sizeof(privkey) == 33: # If compressed
            privkey = int.from_bytes(privkey.to_bytes(33, 'big')[:32], 'big')
        (x, y) = secp256k1.privtopub(privkey.to_bytes(sizeof(privkey), 'big'))
    elif isinstance(privkey, bytes):
        if len(privkey) == 33: # If compressed
            privkey = privkey[:32]
        (x, y) = secp256k1.privtopub(privkey)
    else:
        raise ValueError("privkey must be int or bytes")
    return (x, y)
Exemple #7
0
def ecdsa_priv2pub(privkey: bytes,
                   to_bytes: bool = True) -> Union[bytes, Tuple[int]]:
    """
    Returns the public component of an ECDSA private key.

    :param privkey: Private key as an int or bytestring
    :param to_bytes: Serialize to bytes or not?

    :return: Byte encoded or Tuple[int] ECDSA pubkey
    """
    pubkey = privtopub(privkey)
    if to_bytes:
        return ecdsa_pub2bytes(pubkey)
    return pubkey
Exemple #8
0
    def prestart(self):
        super(ParityServer, self).prestart()

        if self.settings['jsonrpc_port'] is None:
            self.settings['jsonrpc_port'] = get_unused_port()

        if self.version < (1, 7, 0) and self.settings[
                'no_dapps'] is False and self.settings['dapps_port'] is None:
            self.settings['dapps_port'] = get_unused_port()

        if self.settings['node_key'] is None:
            self.settings['node_key'] = "{:0>64}".format(
                binascii.b2a_hex(os.urandom(32)).decode('ascii'))

        pub_x, pub_y = privtopub(binascii.a2b_hex(self.settings['node_key']))
        pub = encode_int32(pub_x) + encode_int32(pub_y)
        self.public_key = "{:0>128}".format(
            binascii.b2a_hex(pub).decode('ascii'))

        # write chain file
        write_chain_file(self.version, self.chainfile, self.faucet,
                         self.difficulty)
Exemple #9
0
def priv_to_pub(k):
    k = normalize_key(k)
    x, y = privtopub(k)
    return bytes(encode_int32(x) + encode_int32(y))
Exemple #10
0
def ec_random_keys():
    priv_key = random.randint(0, 2 ** 256).to_bytes(32, "big")
    pub_key = privtopub(priv_key)
    return priv_key, pub_key
Exemple #11
0
def test_privtopub():
    assert privtopub(priv) == pub
Exemple #12
0
def priv_to_pub(priv):
    x, y = privtopub(priv)
    return x, y
Exemple #13
0
def privkey_to_addr(key):
    key = normalize_key(key)
    x, y = privtopub(key)
    return sha3_256(encode_int32(x) + encode_int32(y))[12:]
Exemple #14
0
def privToPub(priv):
    priv = int(priv, 16).to_bytes(32, 'big')
    res = secp256k1.privtopub(priv)
    x = res[0].to_bytes(32, 'big')
    y = res[1].to_bytes(32, 'big')
    return x + y
Exemple #15
0
from py_ecc.secp256k1 import privtopub, ecdsa_raw_sign, ecdsa_raw_recover
import binascii

priv = binascii.unhexlify(
    '792eca682b890b31356247f2b04662bff448b6bb19ea1c8ab48da222c894ef9b')
pub = (
    20033694065814990006010338153307081985267967222430278129327181081381512401190L,
    72089573118161052907088366229362685603474623289048716349537937839432544970413L
)

assert privtopub(priv) == pub
v, r, s = ecdsa_raw_sign(b'\x35' * 32, priv)
assert ecdsa_raw_recover(b'\x35' * 32, (v, r, s)) == pub
print('secp256k1 tests passed')
Exemple #16
0
def privtoaddr(k):
	k = normalize_key(k)
	x, y = privtopub(k)
	return sha3(encode_int32(x) + encode_int32(y))[12:]
Exemple #17
0
def private_key_to_address(privkey):
    k = normalize_key(privkey)
    x, y = privtopub(k)
    return sha3.keccak_256(encode_int32(x) + encode_int32(y)).digest()[12:]