示例#1
0
 def from_hex(cls, hexed):
     """
     :param hexed: A private key previously encoded as hex.
     :type hexed: ``str``
     :rtype: :class:`~core.PrivateKey`
     """
     return PrivateKey(ECPrivateKey.from_hex(hexed))
示例#2
0
    def generate(cls, xprv=None, prv=None, seed=None, child=None, username=None):
        mnemonic = Mnemonic('english')
        # generate 12 word mnemonic seed
        if not seed and not xprv and not prv:
            seed = mnemonic.generate(256)
        private_key = None
        if seed:
            # create bitcoin wallet
            entropy = mnemonic.to_entropy(seed)
            key = BIP32Key.fromEntropy(entropy)
            private_key = key.PrivateKey().hex()
            extended_key = key.ExtendedKey()
        else:
            raise Exception('No Seed')
        if prv:
            private_key = PrivateKey.from_hex(bytes.fromhex(prv)).to_hex()
            extended_key = ''

        if xprv:
            key = BIP32Key.fromExtendedKey(xprv)
            private_key = key.PrivateKey().hex()
            extended_key = key.ExtendedKey()
        
        if xprv and child:
            for x in child:
                key = key.ChildKey(int(x))
                private_key = key.PrivateKey().hex()

        if not private_key:
            raise Exception('No key')

        return cls({
            "seed": seed or '',
            "xprv": extended_key or '',
            "private_key": private_key,
            "wif": cls.generate_wif(private_key),
            "public_key": PublicKey.from_point(key.K.pubkey.point.x(), key.K.pubkey.point.y()).format().hex(),
            "address": str(key.Address()),
            "serve_host": "0.0.0.0",
            "serve_port": 8000,
            "use_pnp": True,
            "ssl": False,
            "origin": '',
            "polling": 0,
            "post_peer": False,
            # "public_ip": "",  # TODO
            "peer_host": "",
            "peer_port": 8000,
            "web_server_host": "0.0.0.0",
            "web_server_port": 5000,
            "peer": "http://localhost:8000",
            "callbackurl": "http://0.0.0.0:5000/create-relationship",
            "fcm_key": "",
            "database": "yadacoin",
            "site_database": "yadacoinsite",
            "mongodb_host": "localhost",
            "mixpanel": "",
            "username": username or '',
            "network": "mainnet"
        })
示例#3
0
 def from_seed(self,
               seed: str = '',
               subtype: SignerSubType = SignerSubType.MAINNET_REGULAR):
     """Creates key from seed - for ecdsa, seed = pk - 32 bytes random buffer"""
     if subtype != SignerSubType.MAINNET_REGULAR:
         self._subtype = subtype
     if len(seed) > 64:
         # Too long seed, trim (could use better scheme for more entropy)
         seed = seed[:64]
     elif seed == '':
         # No seed, use urandom
         seed = urandom(32)
     elif len(seed) < 64:
         # Too short seed, use as PRNG seed
         random.seed(seed)
         seed = random.getrandbits(32 * 8).hex()
     try:
         key = PrivateKey.from_hex(seed)
         public_key = key.public_key.format(compressed=True).hex()
         # print("Public Key", public_key)
         self._key = key
         self._private_key = key.to_hex()  # == seed
         self._public_key = public_key
     except Exception as e:
         print("Exception {} reading RSA private key".format(e))
     # print("identifier", self.identifier().hex())
     self._address = self.address()
示例#4
0
 def create_signed_transaction(self, func_name, args, nonce_offset=0, value=0):
     tx = self.create_transaction(func_name, args, nonce_offset, value)
     sign_transaction(tx, self.private_key, self.web3.version.network)
     pk = PrivateKey.from_hex(self.private_key[2:])
     tx.sign(pk.secret)
     raw_tx = rlp.encode(tx)
     return self.web3.toHex(raw_tx)
示例#5
0
def add_appointment_misbehaving_tower(appointment, user, tower_sk):
    # This covers a tower signing with invalid keys
    wrong_sk = PrivateKey.from_hex(get_random_value_hex(32))

    wrong_sig = Cryptographer.sign(appointment.serialize(), wrong_sk)
    response, rcode = add_appointment_success(appointment, user, tower_sk)
    user["appointments"][appointment.locator]["signature"] = wrong_sig
    response["signature"] = wrong_sig

    return response, rcode
def test_sign_ground_truth():
    # Generate a signature that has been verified by c-lightning.
    raw_sk = "24e9a981580d27d9277071a8381542e89a7c124868c4e862a13595dc75c6922f"
    sk = PrivateKey.from_hex(raw_sk)

    c_lightning_rpk = "0235293db86c6aaa74aff69ebacad8471d5242901ea9f6a0341a8dca331875e62c"
    message = b"Test message"

    sig = Cryptographer.sign(message, sk)
    rpk = Cryptographer.recover_pk(message, sig)

    assert c_lightning_rpk == Cryptographer.get_compressed_pk(rpk)
示例#7
0
def sign(privkey: str, msg: bytes, v=0) -> bytes:
    assert isinstance(msg, bytes)
    assert isinstance(privkey, str)

    pk = PrivateKey.from_hex(remove_0x_prefix(privkey))
    assert len(msg) == 32

    sig = pk.sign_recoverable(msg, hasher=None)
    assert len(sig) == 65

    sig = sig[:-1] + bytes([sig[-1] + v])

    return sig
示例#8
0
def sign(privkey: str, msg: bytes, v=0) -> bytes:
    assert isinstance(msg, bytes)
    assert isinstance(privkey, str)

    pk = PrivateKey.from_hex(remove_0x_prefix(privkey))
    assert len(msg) == 32

    sig = pk.sign_recoverable(msg, hasher=None)
    assert len(sig) == 65

    sig = sig[:-1] + bytes([sig[-1] + v])

    return sig
示例#9
0
def populate_token_networks(
    token_networks: List[TokenNetwork],
    token_network_contracts: List[Contract],
    addresses: List[Address],
    private_keys: List[str],
) -> None:
    random.seed(NUMBER_OF_CHANNELS)
    # seed for pseudo-randomness from config constant, that changes from time to time
    for token_network in token_networks:
        for channel_id in range(NUMBER_OF_CHANNELS):
            seed1, seed2 = random.sample(private_keys, 2)
            private_key_ecdsa1 = PrivateKey.from_hex(remove_0x_prefix(seed1))
            private_key_ecdsa2 = PrivateKey.from_hex(remove_0x_prefix(seed2))
            address1 = to_checksum_address(
                public_key_to_address(private_key_ecdsa1.public_key))
            address2 = to_checksum_address(
                public_key_to_address(private_key_ecdsa2.public_key))
            fee1 = str(abs(random.gauss(0.0002, 0.0001))).encode()
            fee2 = str(abs(random.gauss(0.0002, 0.0001))).encode()
            signature1 = private_key_ecdsa1.sign_recoverable(fee1)
            signature2 = private_key_ecdsa2.sign_recoverable(fee2)
            token_network.handle_channel_opened_event(channel_id, address1,
                                                      address2)

            # deposit to channels
            deposit1, deposit2 = random.sample(range(1000), 2)
            address1, address2 = token_network.channel_id_to_addresses[
                channel_id]
            token_network.handle_channel_new_deposit_event(
                channel_id, address1, deposit1)
            token_network.handle_channel_new_deposit_event(
                channel_id, address2, deposit2)
            # cuts negative values of probability distribution, fix with > 0 distribution

            token_network.update_fee(channel_id, fee1, signature1)
            token_network.update_fee(channel_id, fee2, signature2)
示例#10
0
 def from_seed(self, seed: str='', subtype: SignerSubType = SignerSubType.MAINNET_REGULAR):
     print('crw from seed {}'.format(seed))
     if subtype != SignerSubType.MAINNET_REGULAR:
         self._subtype = subtype
     try:
         key = PrivateKey.from_hex(seed)
         public_key = key.public_key.format(compressed=False).hex()
         print("Public Key", public_key)
         self._key = key
         self._private_key = key.to_hex()  # == seed
         self._public_key = public_key
     except Exception as e:
         print("Exception {} reading RSA private key".format(e))
     print("identifier", self.identifier().hex())
     self._address = self.address()
示例#11
0
def sign(privkey: str, msg_hash: bytes, v: int = 0) -> bytes:
    if not isinstance(msg_hash, bytes):
        raise TypeError("sign(): msg_hash is not an instance of bytes")
    if len(msg_hash) != 32:
        raise ValueError("sign(): msg_hash has to be exactly 32 bytes")
    if not isinstance(privkey, str):
        raise TypeError("sign(): privkey is not an instance of str")
    if v not in {0, 27}:
        raise ValueError(f"sign(): got v = {v} expected 0 or 27.")

    pk = PrivateKey.from_hex(remove_0x_prefix(privkey))
    sig: bytes = pk.sign_recoverable(msg_hash, hasher=None)
    assert len(sig) == 65

    pub = pk.public_key
    recovered = PublicKey.from_signature_and_message(sig,
                                                     msg_hash,
                                                     hasher=None)
    assert pub == recovered

    sig = sig[:-1] + bytes([sig[-1] + v])

    return sig
示例#12
0
def privkey_to_addr(privkey: str) -> str:
    return to_checksum_address(
        pubkey_to_addr(PrivateKey.from_hex(remove_0x_prefix(privkey)).public_key)
    )
 def to_pubkey(self) -> bytes:
     """Computes and sends back pubkey, point(kpar) of current key(kpar)"""
     kpar = PrivateKey.from_hex(self.seed[:32].hex())
     K = kpar.public_key.format(compressed=False)
     return K
def privatekeyHexToAddress(priv):
    pk = PrivateKey.from_hex(priv)
    publ = pk.public_key.format(compressed=False)[1:]
    return publickeyToAddress(publ)
示例#15
0
def privkey_to_addr(privkey: str) -> str:
    return to_checksum_address(
        pubkey_to_addr(PrivateKey.from_hex(remove_0x_prefix(privkey)).public_key)
    )
示例#16
0
 def generate_signature(self, message, private_key):
     key = PrivateKey.from_hex(private_key)
     signature = key.sign(message.encode("utf-8"))
     return base64.b64encode(signature).decode("utf-8")
示例#17
0
    def generate(cls,
                 xprv=None,
                 prv=None,
                 seed=None,
                 child=None,
                 username=None,
                 mongodb_host=None,
                 db_name=None):
        mnemonic = Mnemonic('english')
        # generate 12 word mnemonic seed
        if not seed and not xprv and not prv:
            seed = mnemonic.generate(256)
        private_key = None
        if seed:
            # create new wallet
            entropy = mnemonic.to_entropy(seed)
            key = BIP32Key.fromEntropy(entropy)
            private_key = key.PrivateKey().hex()
            extended_key = key.ExtendedKey()
            public_key = PublicKey.from_point(
                key.K.pubkey.point.x(), key.K.pubkey.point.y()).format().hex()
            address = str(key.Address())

        if prv:
            key = PrivateKey.from_hex(prv)
            private_key = key.to_hex()
            extended_key = ''
            public_key = key.public_key.format().hex()
            address = str(
                P2PKHBitcoinAddress.from_pubkey(bytes.fromhex(public_key)))

        if xprv:
            key = BIP32Key.fromExtendedKey(xprv)
            private_key = key.PrivateKey().hex()
            extended_key = key.ExtendedKey()
            public_key = PublicKey.from_point(
                key.K.pubkey.point.x(), key.K.pubkey.point.y()).format().hex()
            address = str(key.Address())

        if xprv and child:
            for x in child:
                key = key.ChildKey(int(x))
                private_key = key.PrivateKey().hex()
                public_key = PublicKey.from_point(
                    key.K.pubkey.point.x(),
                    key.K.pubkey.point.y()).format().hex()
                address = str(key.Address())

        if not private_key:
            raise Exception('No key')

        try:
            u = UPnP(None, None, 200, 0)
            u.discover()
            u.selectigd()
            peer_host = u.externalipaddress()
        except:
            try:
                import urllib.request
                peer_host = urllib.request.urlopen(
                    'https://ident.me').read().decode('utf8')
            except:
                peer_host = ''

        return cls({
            "modes": ['node', 'web', 'pool'],
            "root_app": '',
            "seed": seed or '',
            "xprv": extended_key or '',
            "private_key": private_key,
            "wif": cls.generate_wif(private_key),
            "public_key": public_key,
            "address": address,
            "api_whitelist": [],
            "serve_host": "0.0.0.0",
            "serve_port": 8001,
            "use_pnp": False,
            "ssl": False,
            "origin": '',
            "sia_api_key": '',
            "post_peer": False,
            "peer_host": peer_host,
            "peer_port": 8000,
            "peer_type": "user",
            "peer": "http://localhost:8000",
            "callbackurl": "http://0.0.0.0:8001/create-relationship",
            "jwt_public_key": None,
            "fcm_key": "",
            "database": db_name or "yadacoin",
            "site_database": db_name + "site" if db_name else "yadacoinsite",
            "mongodb_host": mongodb_host or "localhost",
            "mixpanel": "",
            "username": username or '',
            "network": "mainnet",
            "wallet_host_port": 'http://localhost:8001',
            "credits_per_share": 5,
            "shares_required": False,
            "pool_payout": False,
            "pool_take": .01,
            "payout_frequency": 6
        })
示例#18
0
auto_parser.add_argument(
    '-c',
    '--create',
    help='Create a new config file if one does not already exist')
auto_parser.add_argument('-m', '--mongo-host', help='Specify a mongodb host')

args = parser.parse_args()

public_ip = requests.get('https://api.ipify.org').text
if args.which == 'new':
    if args.password.value:
        num = from_wif(args.password.value)
    else:
        num = os.urandom(32).encode('hex')
    Config.username = args.username
    pk = PrivateKey.from_hex(num)
    print generate()
elif args.which == 'update':
    with open(args.config) as f:
        identity = json.loads(f.read())
        pk = PrivateKey.from_hex(identity['private_key'])
        if 'username' in identity:
            username = identity['username']
        else:
            username = args.username
        Config.username = username
        print generate()
elif args.which == 'auto':
    num = os.urandom(32).encode('hex')
    pk = PrivateKey.from_hex(num)
    Config.username = ''
 def generate_signature(cls, message):
     key = PrivateKey.from_hex(Config.private_key)
     signature = key.sign(message)
     return base64.b64encode(signature)
示例#20
0
 def __init__(self, private_key):
     self.private_key = PvtKey.from_hex(private_key)
     self.public_key = hexlify(
         self.private_key.public_key.format()).decode()
示例#21
0
 def __init__(self, seed):
     key = PrivateKey.from_hex(seed)
     self.public_key = key.public_key.format(compressed=True).hex()
     self.key = key.to_hex()  # == seed
     self.address = self.address()
示例#22
0
    '--create',
    help='Create a new config file if one does not already exist')
auto_parser.add_argument('-m', '--mongo-host', help='Specify a mongodb host')

args = parser.parse_args()
"""
TODO: add other apis in case this one is down. Allow to override from optional command line param
"""
public_ip = requests.get('https://api.ipify.org').text

if args.which == 'new':
    if args.password.value:
        num = from_wif(args.password.value)
    else:
        num = os.urandom(32).hex()
    pk = PrivateKey.from_hex(num)
    config = Config.generate(pk.to_hex())
    config.username = args.username
elif args.which == 'update':
    with open(args.config) as f:
        identity = json.loads(f.read())
        config = Config.generate(xprv=identity['xprv'])
        if 'username' in identity and identity['username']:
            username = identity['username']
        else:
            username = args.username
        config.username = username
        config.bulletin_secret = config.get_bulletin_secret()
        print(config.to_json())
elif args.which == 'auto':
    config = Config.generate()
示例#23
0
def sign_data(privkey: str, msg: bytes, v=27):
    pk = PrivateKey.from_hex(remove_0x_prefix(privkey))
    sha3 = lambda x: keccak_256(x).digest()
    sig = pk.sign_recoverable(msg, hasher=sha3)
    return sig[:-1] + chr(sig[-1] + v).encode()
示例#24
0
"""
Test bip32 btc like
"""

from coincurve import PrivateKey, PublicKey
from bip32utils import BIP32Key

# seed = os.urandom(32).hex()
seed = "8950b1cffcd85b6ad992feed179863da032b2674178127150db25f5208ea8e4a"
# TEST ONLY, DO NOT USE FOR REAL
print(seed)
pk = PrivateKey.from_hex(seed)
pkhex = pk.to_hex()
print("pkhex", pkhex)  # == SEED

key = BIP32Key.fromEntropy(seed.encode("utf-8"))
private_key = key.PrivateKey().hex()
extended_key = key.ExtendedKey()

public_key = key.PublicKey().hex()
address = key.Address()

print("private_key", private_key)
print("extended_key", extended_key)
print("public_key", public_key)
print("address", address)
identifier = key.Identifier().hex()
print("id", identifier)

priv = "d5ba601c19bfc54e109d20736453ba150f624ee03e2b7a5a3875342cd64d2efe"
seed = "e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35"
示例#25
0
def private_key_to_address(private_key: str) -> Address:
    """ Converts a private key to an Ethereum address. """
    return to_checksum_address(
        public_key_to_address(
            PrivateKey.from_hex(remove_0x_prefix(private_key)).public_key))