Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""
ECDSA
eliptical curve digital signature algorithm
this is where the real hocus pocus lies
all of the ordering, typing, serializing, and digesting
culminates with the message meeting the wif
"""
# 8 bit string representation of private key
p = bytes(PrivateKey(wif))
# create some arbitrary data used by the nonce generation
ndata = secp256k1_ffi.new("const int *ndata")
ndata[0] = 0 # it adds "\0x00", then "\0x00\0x00", etc..
while True: # repeat process until deterministic and cannonical
ndata[0] += 1 # increment the arbitrary nonce
# obtain compiled/binary private key from the wif
privkey = secp256k1_PrivateKey(p, raw=True)
print(it('red',str(privkey)))
print(privkey)
# create a new recoverable 65 byte ECDSA signature
sig = secp256k1_ffi.new(
"secp256k1_ecdsa_recoverable_signature *"
)
# parse a compact ECDSA signature (64 bytes + recovery id)
# returns: 1 = deterministic; 0 = not deterministic
deterministic = secp256k1_lib.secp256k1_ecdsa_sign_recoverable(
privkey.ctx, # initialized context object
sig, # array where signature is held
digest, # 32-byte message hash being signed
privkey.private_key, # 32-byte secret key
secp256k1_ffi.NULL, # default nonce function
ndata, # incrementing nonce data
)
def sign(data: str, private_key_seed_ascii: str):
data = eth_message_hex(data)
print("--eth_message_hex hash", data)
priv = private_key_seed_ascii
pk = PrivateKey(priv, raw=True)
signature = pk.ecdsa_recoverable_serialize(pk.ecdsa_sign_recoverable(data, raw=True))
signature = signature[0] + utils.bytearray_to_bytestr([signature[1]])
return signature, eth_privtoaddr(priv)
:param str wif: Private key in
"""
if not isinstance(message, bytes):
message = bytes(message, "utf-8")
digest = hashfn(message).digest()
priv_key = PrivateKey(wif)
p = bytes(priv_key)
if SECP256K1_MODULE == "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, digest, privkey.private_key, secp256k1.ffi.NULL, ndata
)
if not signed == 1: # pragma: no cover
raise AssertionError()
signature, i = privkey.ecdsa_recoverable_serialize(sig)
if _is_canonical(signature):
i += 4 # compressed
i += 27 # compact
break
elif SECP256K1_MODULE == "cryptography":
cnt = 0
private_key = ec.derive_private_key(
int(repr(priv_key), 16), ec.SECP256K1(), default_backend()
)
def privkey_to_pubkey_inner(priv, usehex):
'''Take 32/33 byte raw private key as input.
If 32 bytes, return compressed (33 byte) raw public key.
If 33 bytes, read the final byte as compression flag,
and return compressed/uncompressed public key as appropriate.'''
compressed, priv = read_privkey(priv)
#secp256k1 checks for validity of key value.
newpriv = secp256k1.PrivateKey(privkey=priv, ctx=ctx)
return newpriv.pubkey.serialize(compressed=compressed)
def add_privkeys(priv1, priv2, usehex):
'''Add privkey 1 to privkey 2.
Input keys must be in binary either compressed or not.
Returned key will have the same compression state.
Error if compression state of both input keys is not the same.'''
y, z = [read_privkey(x) for x in [priv1, priv2]]
if y[0] != z[0]:
raise Exception("cannot add privkeys, mixed compression formats")
else:
compressed = y[0]
newpriv1, newpriv2 = (y[1], z[1])
p1 = secp256k1.PrivateKey(newpriv1, raw=True, ctx=ctx)
res = p1.tweak_add(newpriv2)
if compressed:
res += '\x01'
return res
def new_from_user_input(user_input: Dict[str, Any]) -> "EthereumNetwork": # noqa: C901
"""Create a new EthereumNetwork model from user input
Args:
user_input: User dictionary input (assumed already passing create_ethereum_interchain_schema)
Returns:
Instantiated EthereumNetwork client
Raises:
exceptions.BadRequest: With bad input
"""
dto_version = user_input.get("version")
if dto_version == "1":
if not user_input.get("private_key"):
# We need to create a private key if not provided
user_input["private_key"] = base64.b64encode(secp256k1.PrivateKey().private_key).decode("ascii")
else:
try:
# Check if user provided key is hex and convert if necessary
if len(user_input["private_key"]) == 66: # Ethereum private keys in hex are 66 chars with leading 0x
user_input["private_key"] = user_input["private_key"][2:] # Trim the 0x
if len(user_input["private_key"]) == 64: # Ethereum private keys in hex are 64 chars
user_input["private_key"] = base64.b64encode(bytes.fromhex(user_input["private_key"])).decode("ascii")
except Exception:
# If there's an error here, it's a bad key. Just set it to something bad as bad keys are caught later when making the client
user_input["private_key"] = "a"
# Use preset rpc addresses if user didn't provide one
if not user_input.get("rpc_address"):
if user_input.get("chain_id") == 1:
user_input["rpc_address"] = DRAGONCHAIN_MAINNET_NODE
elif user_input.get("chain_id") == 3:
user_input["rpc_address"] = DRAGONCHAIN_ROPSTEN_NODE
def privkey_to_pubkey_inner(priv, usehex):
'''Take 32/33 byte raw private key as input.
If 32 bytes, return compressed (33 byte) raw public key.
If 33 bytes, read the final byte as compression flag,
and return compressed/uncompressed public key as appropriate.'''
compressed, priv = read_privkey(priv)
#secp256k1 checks for validity of key value.
newpriv = secp256k1.PrivateKey(privkey=priv, ctx=ctx)
return newpriv.pubkey.serialize(compressed=compressed)
def from_hex(cls, hex_encoded_private_key) :
priv = binascii.unhexlify(hex_encoded_private_key)
return cls(secp256k1.PrivateKey(priv))
def CreatePdoSawtoothSigner(private_key_str, pdo_crypto=False):
if not pdo_crypto:
if not private_key_str:
sk = secp256k1.PrivateKey(ctx=__CTX__)
return SignerSecp256k1Lib(sk)
else:
try:
sk = binascii.unhexlify(private_key_str)
return SignerSecp256k1Lib(secp256k1.PrivateKey(sk, ctx = __CTX__))
except Exception as e:
raise ClientConnectException('Unable to parse hex private key: {}'.format(e))
else:
# TODO: add PDO crypto lib support here
raise ClientConnectException('PDO Crypto is not supported')
def sign(data: str, private_key_seed_ascii: str):
data = eth_message_hex(data)
print("--eth_message_hex hash", data)
priv = private_key_seed_ascii
pk = PrivateKey(priv, raw=True)
signature = pk.ecdsa_recoverable_serialize(pk.ecdsa_sign_recoverable(data, raw=True))
signature = signature[0] + utils.bytearray_to_bytestr([signature[1]])
return signature, eth_privtoaddr(priv)