Exemple #1
0
def segwit_sign(tx,
                i,
                priv,
                amount,
                hashcode=SIGHASH_ALL,
                script=None,
                separator_index=None):
    i = int(i)
    txobj = tx if isinstance(tx, dict) else deserialize(tx)
    if not isinstance(tx, dict) and ((not is_python2 and isinstance(re, bytes))
                                     or not re.match('^[0-9a-fA-F]*$', tx)):
        return binascii.unhexlify(sign(binascii.hexlify(tx), i, priv))
    if len(priv) <= 33:
        priv = binascii.hexlify(priv)
    pub = privkey_to_pubkey(priv)
    address = pubkey_to_address(pub)
    wscript = mk_pubkey_script(address) if not script else script
    stripped_script = segwit_strip_script_separator(wscript, separator_index)
    signing_tx = segwit_signature_form(tx,
                                       i,
                                       stripped_script,
                                       amount,
                                       hashcode=hashcode)
    rawsig = ecdsa_raw_sign(
        hashlib.sha256(
            hashlib.sha256(
                binascii.unhexlify(signing_tx)).digest()).hexdigest(), priv)
    sig = der_encode_sig(*rawsig) + encode(hashcode, 16, 2)
    txobj['ins'][i]['txinwitness'] = [sig, pub if not script else script]
    return serialize(txobj)
Exemple #2
0
def segwit_multisign(tx, i, script, pk, amount, hashcode=SIGHASH_ALL, separator_index=None):
    wscript = segwit_strip_script_separator(script, index=separator_index)
    signing_tx = segwit_signature_form(tx, i, wscript, amount, hashcode=hashcode)
    rawsig = ecdsa_raw_sign(hashlib.sha256(hashlib.sha256(
        binascii.unhexlify(signing_tx)).digest()).hexdigest(), pk)
    sig = der_encode_sig(*rawsig)+encode(hashcode, 16, 2)
    return sig
Exemple #3
0
def generate_feed(block_number, nonce, ask_for_1000, bid_for_1000,
                  private_key):
    hexX = h2b("%0.64X" % block_number)
    hexY = h2b("%0.64X" % nonce)
    hexZ = h2b("%0.64X" % ask_for_1000)
    hexW = h2b("%0.64X" % bid_for_1000)
    msg = hexX + hexY + hexZ + hexW
    msghash = b2h(utils.sha3(msg))
    V, R, S = bitcoin.ecdsa_raw_sign(msghash, private_key)
    # print("V R S")
    R = utils.int_to_hex(R)
    S = utils.int_to_hex(S)
    # print("0x%x" % V, R, S)

    dic = {}
    dic['status'] = "success"
    data = {}
    data['block_number'] = block_number
    data['nonce'] = nonce
    data['bid_for_1000'] = bid_for_1000
    data['ask_for_1000'] = ask_for_1000
    data['message'] = "0x" + b2h(msg)
    data['hash'] = "0x" + msghash
    data['signer'] = "0x" + b2h(utils.privtoaddr(private_key))
    data['v'] = V
    data['r'] = R
    data['s'] = S

    dic['data'] = data

    print(json.dumps(dic, indent=4, sort_keys=True))
Exemple #4
0
def test_valid_sigs(setup_ecc):
    for v in vectors['vectors']:
        msg = v['msg']
        sig = v['sig']
        priv = v['privkey']
        assert sig == btc.ecdsa_raw_sign(msg, priv, True, rawmsg=True) + '01'
        #check that the signature verifies against the key(pair)
        pubkey = btc.privtopub(priv)
        assert btc.ecdsa_raw_verify(msg, pubkey, sig[:-2], True, rawmsg=True)
        #check that it fails to verify against corrupted signatures
        for i in [0, 1, 2, 4, 7, 25, 55]:
            #corrupt one byte
            binsig = binascii.unhexlify(sig)
            checksig = binascii.hexlify(binsig[:i] +
                                        chr((ord(binsig[i]) + 1) % 256) +
                                        binsig[i + 1:-1])

            #this kind of corruption will sometimes lead to an assert
            #failure (if the DER format is corrupted) and sometimes lead
            #to a signature verification failure.
            try:
                res = btc.ecdsa_raw_verify(msg,
                                           pubkey,
                                           checksig,
                                           True,
                                           rawmsg=True)
            except:
                continue
            assert res == False
def sign_btc(msghash, priv, pub):
    V, R, S = bitcoin.ecdsa_raw_sign(msghash, priv)
    assert bitcoin.ecdsa_raw_verify(msghash, (V, R, S), pub)
    Q = bitcoin.ecdsa_raw_recover(msghash, (V, R, S))
    assert addr == bitcoin.encode_pubkey(
        Q, 'hex_compressed') if V >= 31 else bitcoin.encode_pubkey(Q, 'hex')
    return (V, R, S)
Exemple #6
0
def sign_tx(raw_tx, index, privkey, version_byte, hashcode, redem=""):
    if (py_version == 3 and isinstance(
            re, bytes)) or not re.match('^[0-9a-fA-F]*$', raw_tx):
        raw_tx = safe_hexlify(raw_tx)
        return binascii.unhexlify(sign_tx(raw_tx, index, privkey, hashcode))

    if version_byte in version_dict["pubkeyhash"].values():
        pubkey = privkey_to_pubkey(privkey)
        signing_tx = sign_form(raw_tx, index,
                               mk_pkscript(version_byte, hash160(pubkey)),
                               hashcode)
    elif version_byte in version_dict["scripthash"].values():
        assert redem != "", "Empty string found in parameter redem ."
        signing_tx = sign_form(raw_tx, index, redem, hashcode)
    else:
        raise ValueError("Unknown version_byte: '%s' ." % version_byte)

    rawsig = ecdsa_raw_sign(bytes.fromhex(txhash(signing_tx, hashcode)),
                            privkey)
    sig = der_encode_sig(*rawsig) + dec2byte(hashcode, 1, mode="big-endian")
    json_tx = raw2json(raw_tx)

    if version_byte in version_dict["pubkeyhash"].values():
        json_tx["vin"][index]["scriptSig"]["hex"] = call_len(
            len(sig)) + sig + call_len(len(pubkey)) + pubkey
    elif version_byte in version_dict["scripthash"].values():
        json_tx["vin"][index]["scriptSig"]["hex"] = deal_sig(
            json_tx["vin"][index]["scriptSig"]["hex"], sig, redem, privkey)
    else:
        raise ValueError("Unknown version_byte: '%s' ." % version_byte)
    return json2raw(json_tx)
Exemple #7
0
def sign_raw_data( raw_data, privatekey ):
   """
   Sign a string of data.
   Return a base64-encoded signature.
   """
   data_hash = get_data_hash( raw_data )

   data_sig_bin = pybitcointools.ecdsa_raw_sign( data_hash, privatekey )
   return pybitcointools.encode_sig( data_sig_bin[0], data_sig_bin[1], data_sig_bin[2] )
Exemple #8
0
def sign_raw_data( raw_data, privatekey ):
   """
   Sign a string of data.
   Return a base64-encoded signature.
   """
   data_hash = get_data_hash( raw_data )

   data_sig_bin = pybitcointools.ecdsa_raw_sign( data_hash, privatekey )
   return pybitcointools.encode_sig( data_sig_bin[0], data_sig_bin[1], data_sig_bin[2] )
Exemple #9
0
def ecdsa_sign_bin(msgbin, priv):
    v, r, s = ecdsa_raw_sign(msgbin, priv)
    sig = encode_sig(v, r, s)
    pubkey = privkey_to_pubkey(wif_to_privkey(priv))

    ok = ecdsa_raw_verify(msgbin, decode_sig(sig), pubkey)
    if not ok:
        raise Exception('Bad signature!')
    return sig
Exemple #10
0
def make_tx_signatures(txs_to_sign, privkey, pubkey):
    signatures = []
    public = []
    for tx_to_sign in txs_to_sign:
        sig = der_encode_sig(
            *ecdsa_raw_sign(tx_to_sign.rstrip(' \t\r\n\0'), privkey))
        signatures.append(sig)
        public.append(pubkey)
    return signatures, public
Exemple #11
0
def ecdsa_sign(msg: str, wif_priv_key: str, dash_network: str):
    """Signs a message with the Elliptic Curve algorithm."""
    v, r, s = bitcoin.ecdsa_raw_sign(electrum_sig_hash(msg), wif_priv_key)
    sig = bitcoin.encode_sig(v, r, s)
    pubkey = bitcoin.privkey_to_pubkey(wif_to_privkey(wif_priv_key, dash_network))

    ok = bitcoin.ecdsa_raw_verify(electrum_sig_hash(msg), bitcoin.decode_sig(sig), pubkey)
    if not ok:
        raise Exception('Bad signature!')
    return sig
Exemple #12
0
    def sign(cls, message, private_key):
        """
        Args:
            message (string): message to sign
            private_key (string): private_key
        """

        v, r, s = bitcoin.ecdsa_raw_sign(message.encode(),
                                         private_key.encode())

        return [v, r, s]
Exemple #13
0
def ecdsa_sign(msg, priv):
    """
    Based on project: https://github.com/chaeplin/dashmnb.
    """
    v, r, s = ecdsa_raw_sign(electrum_sig_hash(msg), priv)
    sig = encode_sig(v, r, s)
    pubkey = privkey_to_pubkey(wif_to_privkey(priv))

    ok = ecdsa_raw_verify(electrum_sig_hash(msg), decode_sig(sig), pubkey)
    if not ok:
        raise Exception('Bad signature!')
    return sig
def ecdsa_sign_raw(msg_raw: bytes, wif_priv_key: str, dash_network: str):
    """Signs raw bytes (a message hash) with the Elliptic Curve algorithm.
    """

    v, r, s = bitcoin.ecdsa_raw_sign(msg_raw, wif_priv_key)
    sig = bitcoin.encode_sig(v, r, s)
    pubkey = bitcoin.privkey_to_pubkey(wif_to_privkey(wif_priv_key, dash_network))

    ok = bitcoin.ecdsa_raw_verify(msg_raw, bitcoin.decode_sig(sig), pubkey)
    if not ok:
        raise Exception('Bad signature!')
    return sig
Exemple #15
0
    def test_ecrecover(self):
        priv = b.sha256('some big long brainwallet password')
        pub = b.privtopub(priv)

        msghash = b.sha256('the quick brown fox jumps over the lazy dog')
        V, R, S = b.ecdsa_raw_sign(msghash, priv)
        assert b.ecdsa_raw_verify(msghash, (V, R, S), pub)

        addr = utils.sha3(b.encode_pubkey(pub, 'bin')[1:])[12:]
        assert utils.privtoaddr(priv) == addr

        result = self.c.test_ecrecover(utils.big_endian_to_int(msghash.decode('hex')), V, R, S)
        assert result == utils.big_endian_to_int(addr)
def ecdsa_sign(msg, priv):
    """
    Based on project: https://github.com/chaeplin/dashmnb with some changes related to usage of bitcoin library.
    """
    v, r, s = bitcoin.ecdsa_raw_sign(electrum_sig_hash(msg), priv)
    sig = bitcoin.encode_sig(v, r, s)
    pubkey = bitcoin.privkey_to_pubkey(wif_to_privkey(priv))

    ok = bitcoin.ecdsa_raw_verify(electrum_sig_hash(msg),
                                  bitcoin.decode_sig(sig), pubkey)
    if not ok:
        raise Exception('Bad signature!')
    return sig
Exemple #17
0
def ecsign(rawhash, key):
    if secp256k1 and hasattr(secp256k1, 'PrivateKey'):
        pk = secp256k1.PrivateKey(key, raw=True)
        signature = pk.ecdsa_recoverable_serialize(
            pk.ecdsa_sign_recoverable(rawhash, raw=True)
        )
        signature = signature[0] + bytearray_to_bytestr([signature[1]])
        v = safe_ord(signature[64]) + 27
        r = big_endian_to_int(signature[0:32])
        s = big_endian_to_int(signature[32:64])
    else:
        v, r, s = ecdsa_raw_sign(rawhash, key)
    return v, r, s
    def test_ecrecover(self):
        priv = b.sha256('some big long brainwallet password')
        pub = b.privtopub(priv)

        msghash = b.sha256('the quick brown fox jumps over the lazy dog')
        V, R, S = b.ecdsa_raw_sign(msghash, priv)
        assert b.ecdsa_raw_verify(msghash, (V, R, S), pub)

        addr = utils.sha3(b.encode_pubkey(pub, 'bin')[1:])[12:]
        assert utils.privtoaddr(priv) == addr

        result = self.c.test_ecrecover(
            utils.big_endian_to_int(msghash.decode('hex')), V, R, S)
        assert result == utils.big_endian_to_int(addr)
Exemple #19
0
    def Sign(message, private_key, public_key):

        Crypto.SetupSignatureCurve()

        hash = hashlib.sha256(binascii.unhexlify(message)).hexdigest()

        v, r, s = bitcoin.ecdsa_raw_sign(hash, private_key)

        rb = bytearray(r.to_bytes(32, 'big'))
        sb = bytearray(s.to_bytes(32, 'big'))

        sig = rb + sb

        return sig
def ecdsa_sign(msg: str, wif_priv_key: str, dash_network: str):
    """Signs a message with the Elliptic Curve algorithm.
    Note: Dash core uses uncompressed public keys, so if the private key passed as an argument
    is of compressed format, convert it to an uncompressed
    """
    # wif_priv_key = wif_privkey_to_uncompressed(wif_priv_key)

    v, r, s = bitcoin.ecdsa_raw_sign(electrum_sig_hash(msg), wif_priv_key)
    sig = bitcoin.encode_sig(v, r, s)
    pubkey = bitcoin.privkey_to_pubkey(wif_to_privkey(wif_priv_key, dash_network))

    ok = bitcoin.ecdsa_raw_verify(electrum_sig_hash(msg), bitcoin.decode_sig(sig), pubkey)
    if not ok:
        raise Exception('Bad signature!')
    return sig
Exemple #21
0
    def test_ecdsa(self):
        # Verifies that a random sample of freshly generated keys don't
        # end up setting the 'flag' bit which replaces 'v'
        # If this test ever fails, the entire premise of this thing is f****d!
        for _ in range(0, 100):
            messageHash = randb256()
            seckey = randb256()
            pubkey = pubkey_to_ethaddr(b.privtopub(seckey))

            sig_t = b.ecdsa_raw_sign(messageHash, seckey)
            sig = sign(messageHash, seckey)
            assert unpack_signature(*sig) == sig_t

            pubkey_v = recover(messageHash, *sig)
            assert pubkey == pubkey_v
Exemple #22
0
def test_ecrecover():
    s = tester.state()
    c = s.abi_contract(ecrecover_code)

    priv = encode_hex(utils.sha3('some big long brainwallet password'))
    pub = bitcoin.privtopub(priv)

    msghash = encode_hex(utils.sha3('the quick brown fox jumps over the lazy dog'))
    V, R, S = bitcoin.ecdsa_raw_sign(msghash, priv)
    assert bitcoin.ecdsa_raw_verify(msghash, (V, R, S), pub)

    addr = utils.big_endian_to_int(utils.sha3(bitcoin.encode_pubkey(pub, 'bin')[1:])[12:])
    assert utils.big_endian_to_int(utils.privtoaddr(priv)) == addr

    result = c.test_ecrecover(utils.big_endian_to_int(decode_hex(msghash)), V, R, S)
    assert result == addr
Exemple #23
0
    def spend(self, owner):
        assert isinstance(owner, (str, bytes))
        assert len(owner) == 20
        # Sign it, so it can be accepted by an address
        messageHash = utils.sha3(owner + self._pubkey)
        V, R, S = b.ecdsa_raw_sign(messageHash, self._seckey)
        recoveredPublicKey = b.ecdsa_raw_recover(messageHash, (V, R, S))
        assert b.pubtoaddr(recoveredPublicKey) == b.privtoaddr(self._seckey)

        # Correctly encoded
        return ", ".join([
            "\"0x%s\"" % (hexlify(self._pubkey), ),
            "%d" % (V, ),
            "\"0x%064X\"" % (R, ),
            "\"0x%064X\"" % (S, ),
        ])
Exemple #24
0
def sign(sk, data):
    """
     Sign some data with a secret key.
    """
    payload = data or {}
    token = []
    payload['created'] = _utc_timestamp()
    encodedPayload = encode64(json.dumps(payload))
    token.append(encodedPayload)

    hash = sha256(encodedPayload)
    v, r, s = ecdsa_raw_sign(hash, sk)
    sigObj = {'v': v, 'r': to_hex(r), 's': to_hex(s)}
    encodedSignature = encode64(json.dumps(sigObj))
    token.append(encodedSignature)
    return '.'.join(token)
Exemple #25
0
def test_ecrecover():
    s = tester.state()
    c = s.abi_contract(ecrecover_code)

    priv = encode_hex(utils.sha3('some big long brainwallet password'))
    pub = bitcoin.privtopub(priv)

    msghash = encode_hex(utils.sha3('the quick brown fox jumps over the lazy dog'))
    V, R, S = bitcoin.ecdsa_raw_sign(msghash, priv)
    assert bitcoin.ecdsa_raw_verify(msghash, (V, R, S), pub)

    addr = utils.big_endian_to_int(utils.sha3(bitcoin.encode_pubkey(pub, 'bin')[1:])[12:])
    assert utils.big_endian_to_int(utils.privtoaddr(priv)) == addr

    result = c.test_ecrecover(utils.big_endian_to_int(decode_hex(msghash)), V, R, S)
    assert result == addr
Exemple #26
0
def segwit_sign(tx, i, priv, amount, hashcode=SIGHASH_ALL, script=None, separator_index=None):
    i = int(i)
    txobj = tx if isinstance(tx, dict) else deserialize(tx)
    if not isinstance(tx, dict) and ((not is_python2 and isinstance(re, bytes)) or not re.match('^[0-9a-fA-F]*$', tx)):
        return binascii.unhexlify(sign(binascii.hexlify(tx), i, priv))
    if len(priv) <= 33:
        priv = binascii.hexlify(priv)
    pub = privkey_to_pubkey(priv)
    address = pubkey_to_address(pub)
    wscript = mk_pubkey_script(address) if not script else script
    stripped_script = segwit_strip_script_separator(wscript, separator_index)
    signing_tx = segwit_signature_form(tx, i, stripped_script, amount, hashcode=hashcode)
    rawsig = ecdsa_raw_sign(hashlib.sha256(hashlib.sha256(binascii.unhexlify(signing_tx)).digest()).hexdigest(), priv)
    sig = der_encode_sig(*rawsig)+encode(hashcode, 16, 2)
    txobj['ins'][i]['txinwitness'] = [sig, pub if not script else script]
    return serialize(txobj)
Exemple #27
0
def bech32_multisign(tx, i, priv, amount, script, hashcode=SIGHASH_ALL):
    from bitcoin import segwit_signature_form, ecdsa_raw_sign, der_encode_sig
    i = int(i)
    if len(priv) <= 33:
        priv = binascii.hexlify(priv)
    signing_tx = segwit_signature_form(tx,
                                       i,
                                       script,
                                       amount,
                                       hashcode=hashcode)
    rawsig = ecdsa_raw_sign(
        hashlib.sha256(
            hashlib.sha256(
                binascii.unhexlify(signing_tx)).digest()).hexdigest(), priv)
    sig = der_encode_sig(*rawsig) + encode(hashcode, 16, 2)
    return sig
Exemple #28
0
def segwit_multisign(tx,
                     i,
                     script,
                     pk,
                     amount,
                     hashcode=SIGHASH_ALL,
                     separator_index=None):
    wscript = segwit_strip_script_separator(script, index=separator_index)
    signing_tx = segwit_signature_form(tx,
                                       i,
                                       wscript,
                                       amount,
                                       hashcode=hashcode)
    rawsig = ecdsa_raw_sign(
        hashlib.sha256(
            hashlib.sha256(
                binascii.unhexlify(signing_tx)).digest()).hexdigest(), pk)
    sig = der_encode_sig(*rawsig) + encode(hashcode, 16, 2)
    return sig
Exemple #29
0
def bech32_sign(tx, i, priv, amount, script=None, hashcode=SIGHASH_ALL):
    from bitcoin import deserialize, segwit_signature_form, ecdsa_raw_sign, der_encode_sig, serialize, compress
    i = int(i)
    txobj = tx if isinstance(tx, dict) else deserialize(tx)
    if len(priv) <= 33:
        priv = binascii.hexlify(priv)
    pub = compress(privkey_to_pubkey(priv))
    script = script or ('76a914' + hash160(binascii.unhexlify(pub)) + '88ac')
    signing_tx = segwit_signature_form(tx,
                                       i,
                                       script,
                                       amount,
                                       hashcode=hashcode)
    rawsig = ecdsa_raw_sign(
        hashlib.sha256(
            hashlib.sha256(
                binascii.unhexlify(signing_tx)).digest()).hexdigest(), priv)
    sig = der_encode_sig(*rawsig) + encode(hashcode, 16, 2)
    txobj['ins'][i]['txinwitness'] = [sig, pub]
    return serialize(txobj)
Exemple #30
0
    def Sign(message, private_key):
        """
        Sign the message with the given private key.

        Args:
            message (str): message to be signed
            private_key (str): 32 byte key as a double digit hex string (e.g. having a length of 64)
        Returns:
            bytearray: the signature of the message.
        """

        hash = hashlib.sha256(binascii.unhexlify(message)).hexdigest()

        v, r, s = bitcoin.ecdsa_raw_sign(hash, private_key)

        rb = bytearray(r.to_bytes(32, 'big'))
        sb = bytearray(s.to_bytes(32, 'big'))

        sig = rb + sb

        return sig
Exemple #31
0
def ecdsa(order, priv_key):

    hashed_order = keccak_256(
        address(order['makerAddress']) + uint(order['makerAmount']) +
        address(order['makerToken']) + address(order['takerAddress']) +
        uint(order['takerAmount']) + address(order['takerToken']) +
        uint(order['nonce']) + uint(order['expiration']))

    magic = keccak_256(b'\x19Ethereum Signed Message:\n32' +
                       hashed_order.digest())
    v, r, s = ecdsa_raw_sign(magic.hexdigest(),
                             hexadecimal.decode_hex(priv_key))
    r = utils.int_to_hex(r)
    s = utils.int_to_hex(s)

    # Ensuring that the parameters are correct length
    if len(r) < 66:
        r = b'0x0' + r[2:]
    if len(s) < 66:
        diff = 66 - len(s)
        s = '0x' + '0' * diff + s[2:]

    return v, r, s
def test_valid_sigs(setup_ecc):
    for v in vectors['vectors']:
        msg = v['msg']
        sig = v['sig']
        priv = v['privkey']
        assert sig == btc.ecdsa_raw_sign(msg, priv, True, rawmsg=True)+'01'
        #check that the signature verifies against the key(pair)
        pubkey = btc.privtopub(priv)
        assert btc.ecdsa_raw_verify(msg, pubkey, sig[:-2], True, rawmsg=True)
        #check that it fails to verify against corrupted signatures
        for i in [0,1,2,4,7,25,55]:
            #corrupt one byte
            binsig = binascii.unhexlify(sig)
            checksig = binascii.hexlify(binsig[:i] + chr(
                (ord(binsig[i])+1) %256) + binsig[i+1:-1])
            
            #this kind of corruption will sometimes lead to an assert
            #failure (if the DER format is corrupted) and sometimes lead
            #to a signature verification failure.
            try:
                res = btc.ecdsa_raw_verify(msg, pubkey, checksig, True, rawmsg=True)
            except:
                continue
            assert res==False
 def sign(self, key):
     rawhash = sha3(rlp.encode(self.serialize(False)))
     self.v, self.r, self.s = ecdsa_raw_sign(rawhash, key)
     self.sender = privtoaddr(key)
     return self
 def sign(self, key):
     rawhash = utils.sha3(self.serialize(False))
     self.v, self.r, self.s = ecdsa_raw_sign(rawhash, key)
     self.sender = utils.privtoaddr(key)
     return self
def sign(h, priv):
    assert len(h) == 32
    V, R, S = bitcoin.ecdsa_raw_sign(h, priv)
    return V,R,S
Exemple #36
0
 def sign_data(self, data, private_key):
     v, r, s = ecdsa_raw_sign(data, private_key)
     return self.i2b(v), self.i2b(r), self.i2b(s)
Exemple #37
0
import sys
from bitcoin import ecdsa_raw_sign, encode_privkey
from sha3 import keccak_256
from getpass import getpass

def is_canonical( sig ):
  return not (sig[1] & 0x80)\
     and not (sig[1] == 0 and not (sig[2] & 0x80))\
     and not (sig[33] & 0x80)\
     and not (sig[33] == 0 and not (sig[34] & 0x80))

priv = getpass("ETH private key: ")
msg = "I lost my EOS genesis key"
msghash = keccak_256(msg).digest()
  
v, r, s = ecdsa_raw_sign(msghash, encode_privkey(priv,'hex').decode('hex'))
signature = '00%02x%064x%064x' % (v,r,s)

print(signature)
sys.exit(0)
if is_canonical(bytearray(signature.decode('hex'))):
    print(signature)
    sys.exit(0)
else:
    print("Error: bad sig")
    sys.exit(1)

Exemple #38
0
def ecdsa_sign(message, privkey):
    s = _encode_sig(*bitcoin.ecdsa_raw_sign(message, privkey))
    return s
Exemple #39
0
key = utils.sha3('cow') # generate private key using 'brain wallet' seed (should be high entropy)
addr = utils.privtoaddr(key) # get address from private key


gen = blocks.genesis({addr: 10**60})



assembly = serpent.compile_to_assembly(open('tester.se').read())
print assembly
code = serpent.assemble(assembly)
print code


msg_hash = utils.sha3('heres a message')
v, r, s = bitcoin.ecdsa_raw_sign(msg_hash, key)
pub = bitcoin.privkey_to_pubkey(key)
verified = bitcoin.ecdsa_raw_verify(msg_hash, (v, r, s), pub)
print verified

tx_make_root = transactions.contract(0,10,10**30, 10**30, code).sign(key)
success, root_contract = processblock.apply_tx(gen, tx_make_root)

#tx_init_root = transactions.Transaction(1, 100, 10**40, root_contract, 0, serpent.encode_datalist([msg_hash, v, r, s])).sign(key)
#tx_init_root = transactions.Transaction(1, 100, 10**40, root_contract, 0, serpent.encode_datalist(['hi', 'bye'])).sign(key)
tx_init_root = transactions.Transaction(1, 100, 10**40, root_contract, 0, serpent.encode_datalist([2, '139dcd5cc79e260272e05147c349ab5f2db3f102', 1])).sign(key)
#tx_init_root = transactions.Transaction(1, 100, 10**40, root_contract, 0, serpent.encode_datalist([2, 1])).sign(key)
print assembly
success, ans = processblock.apply_tx(gen, tx_init_root)
print ans
data = serpent.decode_datalist(ans)
Exemple #40
0
import random
random.seed(12312421412)
from bitcoin import privtopub, encode_pubkey, ecdsa_raw_sign, ecdsa_raw_recover
import time
# import pyximport
# pyximport.install()
#from ecrecover import ecdsa_sign, ecdsa_verify, ecdsa_recover, test_big
from ecdsa_recover import ecdsa_raw_recover as c_ecdsa_raw_recover
from ecdsa_recover import ecdsa_raw_sign as c_ecdsa_raw_sign

priv = ''.join(chr(random.randint(0, 255)) for i in range(32))
pub = privtopub(priv)
msg = ''.join(chr(random.randint(0, 255)) for i in range(32))
vrs = ecdsa_raw_sign(msg, priv)
assert vrs == c_ecdsa_raw_sign(msg, priv)
p = ecdsa_raw_recover(msg, vrs)
p2 = c_ecdsa_raw_recover(msg, vrs)
assert p == p2
assert encode_pubkey(p, 'bin') == pub

def test_ecrecover(rounds = 100):
    st = time.time()
    rounds = 100
    for i in range(rounds):
        p = ecdsa_raw_recover(msg, vrs)
    print 'py took', (time.time() - st)

def test_cecrecover(rounds = 100):
    st = time.time()
    for i in range(rounds):
        p = c_ecdsa_raw_recover(msg, vrs)
Exemple #41
0
 def Sign(self):
     data = rlp.encode(self, Tx.exclude(['v', 's', 'r']))
     hash = sha3.keccak_256(data).digest()
     self.v, self.r, self.s = bitcoin.ecdsa_raw_sign(hash, self.Key)
     self.HexTx = rlp.encode(self).hex()
     return self.HexTx
Exemple #42
0
for i, test in enumerate(mul_tests):
    print 'trying mul_test %i' % i, test
    o1 = substitutes.jacobian_mul_substitute(*test)
    o2 = s.profile(t.k0, c, 0, funid=0, abi=test)
    # assert o1["gas"] == o2["gas"], (o1, o2, test)
    assert o1["output"] == o2["output"], (o1, o2, test)

c = s.contract('ecrecover.se')
print "Starting ecrecover tests"

for i in range(5):
    print 'trying ecrecover_test', vals[i*2], vals[i*2+1]
    k = vals[i*2]
    h = vals[i*2+1]
    V, R, S = b.ecdsa_raw_sign(b.encode(h, 256, 32), k)
    aa = time.time()
    o1 = substitutes.ecrecover_substitute(h, V, R, S)
    print 'sub', time.time() - aa
    a = time.time()
    o2 = s.profile(t.k0, c, 0, funid=0, abi=[h, V, R, S])
    print time.time() - a
    # assert o1["gas"] == o2["gas"], (o1, o2, h, V, R, S)
    assert o1["output"] == o2["output"], (o1, o2, h, V, R, S)

# Explicit tests

data = [[
    0xf007a9c78a4b2213220adaaf50c89a49d533fbefe09d52bbf9b0da55b0b90b60,
    0x1b,
    0x5228fc9e2fabfe470c32f459f4dc17ef6a0a81026e57e4d61abc3bc268fc92b5,
def mk_sig(hash, priv): return list(b.ecdsa_raw_sign(hash, priv))
def mk_mk_sig(msghash): return (lambda p: mk_sig(msghash, p["priv"]))