Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# address = '0xa5df35f30ba0ce878b1061ae086289adff3ba1e0'
address = web3.personal.importRawKey(private_key, "password")
web3.personal.unlockAccount(address, "password")
assert add_0x_prefix(encode_hex(privtoaddr(private_key))) == add_0x_prefix(address)
assert address == '0xa5df35f30ba0ce878b1061ae086289adff3ba1e0'
# the data to be signed
data = b'1234567890abcdefghijklmnopqrstuvwxyz'
# the hash of the data `0x089c33d56ed10bd8b571a0f493cedb28db1ae0f40c6cd266243001528c06eab3`
data_hash = web3.sha3(data, encoding=None)
data_hash_bytes = decode_hex(data_hash)
assert force_bytes(data_hash) == sha3(data)
priv_key = PrivateKey(flags=ALL_FLAGS)
priv_key.set_raw_privkey(private_key)
# sanit check the extract_ecdsa_signer function works as expected.
vector_sig = priv_key.ecdsa_sign_recoverable(data_hash_bytes, raw=True, digest=hashlib.sha3_256)
vector_sig_bytes, rec_id = priv_key.ecdsa_recoverable_serialize(vector_sig)
vector_sig_bytes_full = vector_sig_bytes + force_bytes(chr(rec_id))
vector_address = force_text(extract_ecdsa_signer(data_hash_bytes, vector_sig_bytes_full))
assert vector_address == address
# Now have geth sign some data.
signature_hex = web3.eth.sign(address, data)
signature_bytes = decode_hex(signature_hex)
# geth prefix message before signing
geth_prefix_data = eth_message_prefix_hash(web3, data.decode())
addr.tags.append(('h', trim_to_bytes(tagdata)))
elif tag == 'x':
addr.tags.append(('x', tagdata.uint))
elif tag == 'p':
if data_length != 52:
addr.unknown_tags.append((tag, tagdata))
continue
addr.paymenthash = trim_to_bytes(tagdata)
elif tag == 'n':
if data_length != 53:
addr.unknown_tags.append((tag, tagdata))
continue
addr.pubkey = secp256k1.PublicKey(flags=secp256k1.ALL_FLAGS)
addr.pubkey.deserialize(trim_to_bytes(tagdata))
elif tag == 'c':
addr.min_final_cltv_expiry = tagdata.uint
else:
addr.unknown_tags.append((tag, tagdata))
# BOLT #11:
#
# A reader MUST check that the `signature` is valid (see the `n` tagged
# field specified below).
if addr.pubkey: # Specified by `n`
# BOLT #11:
#
# A reader MUST use the `n` field to validate the signature instead of
# performing signature recovery if a valid `n` field is provided.
# TODO: This conversion isn't really necessary.
# TODO: Invesitage if the check below is really needed.
v = msg.data.extract32(32)
r = msg.data.extract32(64)
s = msg.data.extract32(96)
if r >= bitcoin.N or s >= bitcoin.N or v < 27 or v > 28:
return 1, msg.gas - opcodes.GECRECOVER, []
signature_bytes = [0] * 64
msg.data.extract_copy(signature_bytes, 0, 64, 32)
msg.data.extract_copy(signature_bytes, 32, 96, 32)
signature = b''.join(map(ascii_chr, signature_bytes))
pk = PublicKey(flags=ALL_FLAGS)
try:
pk.public_key = pk.ecdsa_recover(
message_hash,
pk.ecdsa_recoverable_deserialize(
signature,
v - 27
),
raw=True
)
except Exception:
# Recovery failed
return 1, msg.gas - gas_cost, []
pub = pk.serialize(compressed=False)
o = [0] * 12 + [safe_ord(x) for x in utils.sha3(pub[1:])[-20:]]
return 1, msg.gas - gas_cost, o
def sender(self):
if not self._sender:
# Determine sender
if self.v:
if self.r >= N or self.s >= N or self.v < 27 or self.v > 28 \
or self.r == 0 or self.s == 0:
raise InvalidTransaction("Invalid signature values!")
log.debug('recovering sender')
rlpdata = rlp.encode(self, UnsignedTransaction)
rawhash = utils.sha3(rlpdata)
pk = PublicKey(flags=ALL_FLAGS)
try:
pk.public_key = pk.ecdsa_recover(
rawhash,
pk.ecdsa_recoverable_deserialize(
zpad("".join(chr(c) for c in int_to_32bytearray(self.r)), 32) + zpad("".join(chr(c) for c in int_to_32bytearray(self.s)), 32),
self.v - 27
),
raw=True
)
pub = pk.serialize(compressed=False)
except Exception:
raise InvalidTransaction("Invalid signature values (x^3+7 is non-residue)")
if pub[1:] == "\x00" * 32:
raise InvalidTransaction("Invalid signature (zero privkey cannot sign)")
pub = encode_pubkey(pub, 'bin')
def __init__(self, privkey=None, raw=True, flags=None, ctx=None):
if USE_SECP:
if flags == None:
flags = secp256k1.ALL_FLAGS
self.obj = secp256k1.PrivateKey(privkey, raw, flags, ctx)
self.pubkey = self.obj.pubkey
else:
if not raw:
raise Exception("Non raw init unsupported")
if privkey == None:
privkey = ecpy.ecrand.rnd(CURVE_SECP256K1.order)
else:
privkey = int.from_bytes(privkey,'big')
self.obj = ECPrivateKey(privkey, CURVE_SECP256K1)
pubkey = self.obj.get_public_key().W
out = b"\x04"
out += pubkey.x.to_bytes(32, 'big')
out += pubkey.y.to_bytes(32, 'big')
self.pubkey = PublicKey(out, raw=True)
def recover_sender(self):
if self.v:
if self.r >= N or self.s >= P or self.v < 27 or self.v > 28 \
or self.r == 0 or self.s == 0:
raise InvalidSignature()
rlpdata = rlp.encode(self, self.__class__.exclude(['v', 'r', 's']))
rawhash = sha3(rlpdata)
pk = PublicKey(flags=ALL_FLAGS)
try:
pk.public_key = pk.ecdsa_recover(
rawhash,
pk.ecdsa_recoverable_deserialize(
zpad(
"".join(chr(c) for c in int_to_32bytearray(self.r)),
32
) + zpad(
"".join(chr(c) for c in int_to_32bytearray(self.s)),
32
),
self.v - 27
),
raw=True
)
pub = pk.serialize(compressed=False)
# limitations under the License.
# ------------------------------------------------------------------------------
import binascii
import warnings
import secp256k1
from sawtooth_signing.core import SigningError
from sawtooth_signing.core import ParseError
from sawtooth_signing.core import PrivateKey
from sawtooth_signing.core import PublicKey
from sawtooth_signing.core import Context
__CONTEXTBASE__ = secp256k1.Base(ctx=None, flags=secp256k1.ALL_FLAGS)
__CTX__ = __CONTEXTBASE__.ctx
__PK__ = secp256k1.PublicKey(ctx=__CTX__) # Cache object to use as factory
class Secp256k1PrivateKey(PrivateKey):
def __init__(self, secp256k1_private_key):
self._private_key = secp256k1_private_key
def get_algorithm_name(self):
return "secp256k1"
def as_hex(self):
return binascii.hexlify(self.as_bytes()).decode()
def as_bytes(self):
return bytes(self._private_key.private_key)