コード例 #1
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
コード例 #2
0
ファイル: test_contracts.py プロジェクト: Aireed/pyethereum
def test_ecrecover():
    s = tester.state()
    c = s.abi_contract(ecrecover_code)

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

    msghash = utils.sha3('the quick brown fox jumps over the lazy dog')

    pk = PrivateKey(priv, raw=True)
    signature = pk.ecdsa_recoverable_serialize(
        pk.ecdsa_sign_recoverable(msghash, raw=True)
    )
    signature = signature[0] + utils.bytearray_to_bytestr([signature[1]])
    V = utils.safe_ord(signature[64]) + 27
    R = big_endian_to_int(signature[0:32])
    S = big_endian_to_int(signature[32:64])

    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(msghash), V, R, S)
    assert result == addr
コード例 #3
0
def verify_data_and_signature(signed_transaction: SignedTransaction,
                              transaction: Transaction) -> None:
    """
    Verify received SignedTransaction data and signature and handle related errors.

    1. Check if received SignedTransaction data match original Ethereum Transacion.
    2. Check if received signature is created for given message with given keys pair.
    """

    assert isinstance(signed_transaction, SignedTransaction)
    assert isinstance(transaction, Transaction)

    if not is_signed_transaction_data_equal_to_transaction_data(
            signed_transaction, transaction):
        raise SCICallbackPayloadError(
            'Received SignedTransaction does not match TransactionSigningRequest.'
        )

    # If the Ethereum signature in SignedTransaction is not a valid signature or
    # or the transaction in SignedTransaction is not signed with the right Ethereum private key.
    message_hash = sha3(encode(transaction, UnsignedTransaction))

    if not ecdsa_raw_verify(
            message_hash,
        (
            signed_transaction.v,
            signed_transaction.r,
            signed_transaction.s,
        ),
            settings.CONCENT_ETHEREUM_PUBLIC_KEY,
    ):
        raise SCICallbackTransactionSignatureError(
            'Received SignedTransaction signature data is not signed by right Ethereum private key.'
        )
コード例 #4
0
def test_ecrecover():
    s = tester.state()
    c = s.abi_contract(ecrecover_code)

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

    msghash = utils.sha3('the quick brown fox jumps over the lazy dog')

    pk = PrivateKey(priv, raw=True)
    signature = pk.ecdsa_recoverable_serialize(
        pk.ecdsa_sign_recoverable(msghash, raw=True))
    signature = signature[0] + utils.bytearray_to_bytestr([signature[1]])
    V = utils.safe_ord(signature[64]) + 27
    R = big_endian_to_int(signature[0:32])
    S = big_endian_to_int(signature[32:64])

    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(msghash), V, R, S)
    assert result == addr
コード例 #5
0
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)
コード例 #6
0
 def verify_dc_sig(self, sig, msghash, msgsize, from_addr, data):
     # data comes in as array of byte array (bytes as ints, from js)
     tohash = byte_arrays_to_string(data)
     assert (msghash == utils.sha3(tohash))
     X, Y = ecdsa_raw_recover(msghash, sig)
     pX = utils.int_to_big_endian(X).encode('hex')
     pY = utils.int_to_big_endian(Y).encode('hex')
     pub = '04' + pX + pY
     return ecdsa_raw_verify(msghash, sig, pub.decode('hex'))
コード例 #7
0
 def verify_dc_sig(self, sig, msghash, msgsize, from_addr, data):
     # data comes in as array of byte array (bytes as ints, from js)
     tohash = byte_arrays_to_string(data)
     assert (msghash == utils.sha3(tohash))
     X, Y = ecdsa_raw_recover(msghash, sig)
     pX = utils.int_to_big_endian(X).encode('hex')
     pY = utils.int_to_big_endian(Y).encode('hex')
     pub = '04'+pX+pY
     return ecdsa_raw_verify(msghash, sig, pub.decode('hex'))
コード例 #8
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
コード例 #9
0
ファイル: segwit.py プロジェクト: irmaster/pybitcointools
def segwit_verify_tx_input(tx, i, script, sig, pub, amount):
    hashcode = decode(sig[-2:], 16)
    signing_tx = segwit_signature_form(tx,
                                       int(i),
                                       script,
                                       amount,
                                       hashcode=hashcode)
    hashed_signing_tx = hashlib.sha256(
        hashlib.sha256(binascii.unhexlify(signing_tx)).digest()).hexdigest()
    return ecdsa_raw_verify(hashed_signing_tx, der_decode_sig(sig), pub)
コード例 #10
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
コード例 #11
0
def verify_raw_data( raw_data, pubkey, sigb64 ):
   """
   Verify the signature over a string, given the public key
   and base64-encode signature.
   Return True on success.
   Return False on error.
   """

   data_hash = get_data_hash( raw_data )

   return pybitcointools.ecdsa_raw_verify( data_hash, pybitcointools.decode_sig( sigb64 ), pubkey )
コード例 #12
0
ファイル: storage.py プロジェクト: paulpw/blockstack-cli
def verify_raw_data( raw_data, pubkey, sigb64 ):
   """
   Verify the signature over a string, given the public key
   and base64-encode signature.
   Return True on success.
   Return False on error.
   """

   data_hash = get_data_hash( raw_data )

   return pybitcointools.ecdsa_raw_verify( data_hash, pybitcointools.decode_sig( sigb64 ), pubkey )
コード例 #13
0
def verify(msghash: bytes, signature, public_key):
    """Verify that data has been signed with Etheruem private key.
    :param signature:
    :return:
    """

    V = utils.safe_ord(signature[64]) + 27
    R = big_endian_to_int(signature[0:32])
    S = big_endian_to_int(signature[32:64])

    return bitcoin.ecdsa_raw_verify(msghash, (V, R, S), public_key)
コード例 #14
0
ファイル: sign.py プロジェクト: websauna/websauna.wallet
def verify(msghash: bytes, signature, public_key):
    """Verify that data has been signed with Etheruem private key.
    :param signature:
    :return:
    """

    V = utils.safe_ord(signature[64]) + 27
    R = big_endian_to_int(signature[0:32])
    S = big_endian_to_int(signature[32:64])

    return bitcoin.ecdsa_raw_verify(msghash, (V, R, S), public_key)
コード例 #15
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
コード例 #16
0
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
コード例 #17
0
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
コード例 #18
0
ファイル: test_ecrecover.py プロジェクト: orbro/eth-enablers
    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)
コード例 #19
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)
コード例 #20
0
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
コード例 #21
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
コード例 #22
0
ファイル: test_contracts.py プロジェクト: 4gn3s/pyethereum
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
コード例 #23
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
コード例 #24
0
        def get_result(result):
            try:
                if result[0] and digest(result[1][0]) == contract_hash:
                    contract = json.loads(result[1][0], object_pairs_hook=OrderedDict)

                    # TODO: verify the guid in the contract matches this node's guid
                    signature = contract["vendor_offer"]["signatures"]["guid"]
                    pubkey = node_to_ask.signed_pubkey[64:]
                    verify_obj = json.dumps(contract["vendor_offer"]["listing"], indent=4)

                    verify_key = nacl.signing.VerifyKey(pubkey)
                    verify_key.verify(verify_obj, base64.b64decode(signature))

                    bitcoin_key = contract["vendor_offer"]["listing"]["id"]["pubkeys"]["bitcoin"]
                    bitcoin_sig = contract["vendor_offer"]["signatures"]["bitcoin"]
                    valid = bitcoin.ecdsa_raw_verify(verify_obj, bitcoin.decode_sig(bitcoin_sig), bitcoin_key)
                    if not valid:
                        raise Exception("Invalid Bitcoin signature")

                    if "moderators" in contract["vendor_offer"]["listing"]:
                        for moderator in contract["vendor_offer"]["listing"]["moderators"]:
                            guid = moderator["guid"]
                            guid_key = moderator["pubkeys"]["signing"]["key"]
                            guid_sig = base64.b64decode(moderator["pubkeys"]["signing"]["signature"])
                            enc_key = moderator["pubkeys"]["encryption"]["key"]
                            enc_sig = base64.b64decode(moderator["pubkeys"]["encryption"]["signature"])
                            bitcoin_key = moderator["pubkeys"]["bitcoin"]["key"]
                            bitcoin_sig = base64.b64decode(moderator["pubkeys"]["bitcoin"]["signature"])
                            h = nacl.hash.sha512(guid_sig + unhexlify(guid_key))
                            pow_hash = h[64:128]
                            if int(pow_hash[:6], 16) >= 50 or guid != h[:40]:
                                raise Exception('Invalid GUID')
                            verify_key = nacl.signing.VerifyKey(guid_key, encoder=nacl.encoding.HexEncoder)
                            verify_key.verify(unhexlify(guid_key), guid_sig)
                            verify_key.verify(unhexlify(enc_key), enc_sig)
                            verify_key.verify(unhexlify(bitcoin_key), bitcoin_sig)
                            #TODO: should probably also validate the handle here.
                    self.cache(result[1][0])
                    if "image_hashes" in contract["vendor_offer"]["listing"]["item"]:
                        for image_hash in contract["vendor_offer"]["listing"]["item"]["image_hashes"]:
                            self.get_image(node_to_ask, unhexlify(image_hash))
                    return contract
                else:
                    return None
            except Exception:
                return None
コード例 #25
0
def test_ecrecover():
    c = tester.Chain()
    x = c.contract(ecrecover_code, language='serpent')

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

    msghash = utils.sha3('the quick brown fox jumps over the lazy dog')

    V, R, S = utils.ecsign(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 = x.test_ecrecover(utils.big_endian_to_int(msghash), V, R, S)
    assert result == addr
コード例 #26
0
        def proxyfunc(self, *args, **kw):
            
            self._current_user = {}
            
            #
            ## Get read authorization via encrypted cookies.
            ## Only for reading pending your own pending blind data:
            #

            if not needs_write: ## Don't bother checking for read if write is needed.
                
                cook = self.get_secure_cookie('auth')
                
                if cook:
                    h2 = json.loads(cook)
                    if (time() - h2['created'] <= cookie_expiration_time):
                        self._current_user = {'pub':h2['pub'],
                                              'has_read': True,
                                              'has_write': False,
                                              }
            
            #   
            ## Write authorization, must have valid monotonically increasing nonce:
            #
            
            try:
                hh = json.loads(self.request.body)
            except:
                hh = False
            
            if hh:
                print ('AUTH_CHECK_USER', hh['pub'][:32])

                hh['payload_decoded'] = json.loads(hh['payload'])
                
                if (hh['pub'] in self.cccoin.DBL['LATEST_NONCE']) and \
                   ('nonce' in hh['payload_decoded']) and \
                   (hh['payload_decoded']['nonce'] <= self.cccoin.DBL['LATEST_NONCE'][hh['pub']]
                   ):
                    print ('OUTDATED NONCE')
                    self.write_json({'error':'AUTH_OUTDATED_NONCE'})
                    return
                
                #LATEST_NONCE[user_key] = hh['payload_decoded']['nonce']
                
                is_success = btc.ecdsa_raw_verify(btc.sha256(hh['payload'].encode('utf8')),
                                                  (hh['sig']['sig_v'],
                                                   btc.decode(hh['sig']['sig_r'],16),
                                                   btc.decode(hh['sig']['sig_s'],16),
                                                  ),
                                                  hh['pub'],
                                                  )
                
                if is_success:
                    ## write auth overwrites read auth:
                    self._current_user = {'pub':hh['pub'],
                                          'has_read': True,
                                          'has_write': True,
                                          'write_data': hh,
                                          }
            
            if needs_read and not self._current_user.get('has_read'):
                print ('AUTH_FAILED_READ')
                self.write_json({'error':'AUTH_FAILED_READ'})
                #raise tornado.web.HTTPError(403)
                return
            
            if needs_write and not self._current_user.get('has_write'):
                print ('AUTH_FAILED_READ')
                self.write_json({'error':'AUTH_FAILED_READ'})
                #raise tornado.web.HTTPError(403)
                return
            
            ## TODO: per-public-key sponsorship rate throttling:
            
            self.add_header('X-RATE-USED','0')
            self.add_header('X-RATE-REMAINING','100')
            
            print ('AUTH_FINISHED', self._current_user)
            
            func(self, *args, **kw)
            
            return
コード例 #27
0
    def post(self):

        hh = json.loads(self.request.body)
        
        """
        {the_pub: the_pub,
	 challenge: dd,
	 sig_v: sig.v,
	 sig_r: sig.r.toString('hex'),
	 sig_s: sig.s.toString('hex')
	}
        """
        
        the_pub = hh['the_pub']
        
        challenge = self.cccoin.DBL['CHALLENGES_DB'].get(the_pub, False)
        
        if challenge is False:
            print ('LOGIN_2: ERROR UNKNOWN CHALLENGE', challenge)
            self.write_json({"success":False,
	                     "username_success":False,
	                     "password_success":False,
	                     "got_username":"",
	                     "message":'Unknown or expired challenge during login.',
	                     })
            return
        
        print 'GOT=============='
        print json.dumps(hh, indent=4)
        print '================='
        
        ## Check challenge response, i.e. if password is good:
        
        password_success = btc.ecdsa_raw_verify(btc.sha256(challenge.encode('utf8')),
                                                (hh['sig']['sig_v'],
                                                 btc.decode(hh['sig']['sig_r'],16),
                                                 btc.decode(hh['sig']['sig_s'],16)),
                                                the_pub,
                                                )
        
        ## Check for immediate rejection of username request:
        
        username_success = True
        if hh['requested_username'] and (hh['requested_username'] in self.cccoin.DBL['TAKEN_USERNAMES_DB']):
            username_success = False
        
        if hh['requested_username'] and self.cccoin.tdb.lookup('username_to_user_id',
                                                               T_ANY_FORK,
                                                               hh['requested_username'],
                                                               default=False,
                                                               ):
            username_success = False

        ## Check if user already registered a username before:

        uu = self.cccoin.tdb.lookup('user_id_to_username',
                                    T_ANY_FORK,
                                    the_pub,
                                    default = False,
                                    )
        
        if uu:
            got_username = hh['requested_username']
            username_success = True
        else:
            got_username = hh['requested_username']
        
        self.cccoin.tdb.store('user_id_to_username',
                              'DIRECT',
                              the_pub,
                              hh['requested_username'],
                              start_block = self.cccoin.cw.c.eth_blockNumber(),
                              )

        xx = self.cccoin.tdb.lookup('user_id_to_username',
                                    T_ANY_FORK,
                                    the_pub,
                                    )
        assert xx[0] == hh['requested_username'], xx
        
        ## Check if previously unseen user ID:
        
        is_new = self.cccoin.DBL['SEEN_USERS_DB'].get(the_pub, False)
        
        ## Write out results:
        
        print ('LOGIN_2_RESULT','username_success:', username_success, 'password_success:', password_success)
        
        if (username_success and password_success):
            self.set_secure_cookie('auth', json.dumps({'created':int(time()),
                                                       'pub':the_pub,
                                                       'address':pub_to_address(the_pub),
                                                       }))
            self.cccoin.DBL['SEEN_USERS_DB'][the_pub] = True
        
        self.write_json({"success":password_success,
	                 "username_success":username_success,
	                 "password_success":password_success,
	                 "got_username":got_username,
	                 "message":'',
                         'is_new':is_new,
	                 })
コード例 #28
0
ファイル: keys.py プロジェクト: fcracker79/python_bitcoin_101
import bitcoin

from bitcoin_101 import bitprint

if __name__ == '__main__':
    key = bitcoin.random_key()
    bitprint('Private key:', key)
    pub_key = bitcoin.privtopub(key)
    pub_compact_key = bitcoin.privtopub(key + '01')
    bitprint('Public key:', pub_key)
    bitprint('Public compact key:', pub_compact_key)
    signature = bitcoin.ecdsa_raw_sign(b'a message', key)
    bitprint('Signature verified:',
             bitcoin.ecdsa_raw_verify(b'a message', signature, pub_key))
    bitprint(
        'Signature verified with compact public key:',
        bitcoin.ecdsa_raw_verify(b'a message', signature, pub_compact_key))

    bitprint('Address:', bitcoin.pubtoaddr(pub_key))
    bitprint('Address (compact):', bitcoin.pubtoaddr(pub_compact_key))
コード例 #29
0
def pad32(n):
    if type(n) == str:
        h = n.encode('hex')
    else:
        h = "%02x" % n
    l = len(h)
    return "0" * (32 - l) + h


nargs = pad32(1)
d0 = pad32('hi')
print nargs, d0
msg_hash = utils.sha3(nargs + d0)
v, r, s = bitcoin.ecdsa_raw_sign(msg_hash, key)
pubkey = bitcoin.privkey_to_pubkey(key)
verified = bitcoin.ecdsa_raw_verify(msg_hash, (v, r, s), pubkey)

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

print serpent.compile_to_assembly(open("DAOist frame.se").read())
DAOcode = serpent.compile(open("DAOist frame.se").read())

DAOcontract = transactions.contract(0, 1, 10**12, 100, DAOcode)

DAOcontract.sign(key)

success, contract_address = processblock.apply_tx(gen, DAOcontract)

DCP = transactions.Transaction(
    1, 10**12, 10000, contract_address, 0,
    serpent.encode_datalist([1, 1, v, r, s, 1, 'hi']))
コード例 #30
0
        def get_result(result):
            try:
                if result[0] and digest(result[1][0]) == contract_hash:
                    contract = json.loads(result[1][0],
                                          object_pairs_hook=OrderedDict)

                    # TODO: verify the guid in the contract matches this node's guid
                    signature = contract["vendor_offer"]["signatures"]["guid"]
                    pubkey = node_to_ask.signed_pubkey[64:]
                    verify_obj = json.dumps(
                        contract["vendor_offer"]["listing"], indent=4)

                    verify_key = nacl.signing.VerifyKey(pubkey)
                    verify_key.verify(verify_obj, base64.b64decode(signature))

                    bitcoin_key = contract["vendor_offer"]["listing"]["id"][
                        "pubkeys"]["bitcoin"]
                    bitcoin_sig = contract["vendor_offer"]["signatures"][
                        "bitcoin"]
                    valid = bitcoin.ecdsa_raw_verify(
                        verify_obj, bitcoin.decode_sig(bitcoin_sig),
                        bitcoin_key)
                    if not valid:
                        raise Exception("Invalid Bitcoin signature")

                    if "moderators" in contract["vendor_offer"]["listing"]:
                        for moderator in contract["vendor_offer"]["listing"][
                                "moderators"]:
                            guid = moderator["guid"]
                            guid_key = moderator["pubkeys"]["signing"]["key"]
                            guid_sig = base64.b64decode(
                                moderator["pubkeys"]["signing"]["signature"])
                            enc_key = moderator["pubkeys"]["encryption"]["key"]
                            enc_sig = base64.b64decode(
                                moderator["pubkeys"]["encryption"]
                                ["signature"])
                            bitcoin_key = moderator["pubkeys"]["bitcoin"][
                                "key"]
                            bitcoin_sig = base64.b64decode(
                                moderator["pubkeys"]["bitcoin"]["signature"])
                            h = nacl.hash.sha512(guid_sig +
                                                 unhexlify(guid_key))
                            pow_hash = h[64:128]
                            if int(pow_hash[:6], 16) >= 50 or guid != h[:40]:
                                raise Exception('Invalid GUID')
                            verify_key = nacl.signing.VerifyKey(
                                guid_key, encoder=nacl.encoding.HexEncoder)
                            verify_key.verify(unhexlify(guid_key), guid_sig)
                            verify_key.verify(unhexlify(enc_key), enc_sig)
                            verify_key.verify(unhexlify(bitcoin_key),
                                              bitcoin_sig)
                            #TODO: should probably also validate the handle here.
                    self.cache(result[1][0])
                    if "image_hashes" in contract["vendor_offer"]["listing"][
                            "item"]:
                        for image_hash in contract["vendor_offer"]["listing"][
                                "item"]["image_hashes"]:
                            self.get_image(node_to_ask, unhexlify(image_hash))
                    return contract
                else:
                    return None
            except Exception:
                return None
コード例 #31
0
ファイル: crypto.py プロジェクト: reklaim/pydevp2p
def ecdsa_verify(pubkey, signature, message):
    assert len(signature) == 65
    assert len(pubkey) == 64
    return bitcoin.ecdsa_raw_verify(message, _decode_sig(signature), pubkey)
コード例 #32
0
def ecdsa_verify(pubkey, signature, message):
    assert len(signature) == 65
    assert len(pubkey) == 64
    return bitcoin.ecdsa_raw_verify(message, _decode_sig(signature), pubkey)
コード例 #33
0

def fast_substract(a, b):
    x1, y1 = a
    x2, y2 = b
    return fast_add((x1, y1), (x2, -y2))


inv = bitcoin.inv

# We don't know d but we can get Q from emitted signatures
d = bitcoin.decode_privkey(bitcoin.random_key())
Q = fast_multiply(G, d)

# We build up a message to sign
msghash = hashlib.sha256('a_random_message').hexdigest()
z = bitcoin.hash_to_int(msghash)

cpt = 0
while True:
    cpt = cpt + 1
    r = random.SystemRandom().randrange(1, N)
    s = random.SystemRandom().randrange(1, N / 2)
    if r == fast_add(fast_multiply(G, z * inv(s, N)),
                     fast_multiply(Q, r * inv(s, N)))[0]:
        break

assert bitcoin.ecdsa_raw_verify(msghash, (27, r, s), Q)
print('v={0}\nr={1}\ns={2}'.format(27, r, s))
print('Find after {} attempts.'.format(cpt))
コード例 #34
0
ファイル: tester.py プロジェクト: ebuchman/daoist_protocol

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)
print data
print hex(data[0])
コード例 #35
0
def sign(h, priv):
    assert len(h) == 32
    pub = bitcoin.privtopub(priv)
    V, R, S = bitcoin.ecdsa_raw_sign(h, priv)
    assert bitcoin.ecdsa_raw_verify(h, (V, R, S), pub)
    return V, R, S
コード例 #36
0
ファイル: segwit.py プロジェクト: conio/pybitcointools
def segwit_verify_tx_input(tx, i, script, sig, pub, amount):
    hashcode = decode(sig[-2:], 16)
    signing_tx = segwit_signature_form(tx, int(i), script, amount, hashcode=hashcode)
    hashed_signing_tx = hashlib.sha256(hashlib.sha256(binascii.unhexlify(signing_tx)).digest()).hexdigest()
    return ecdsa_raw_verify(hashed_signing_tx, der_decode_sig(sig), pub)
コード例 #37
0
def apply_op(block, tx, msg, code, compustate):
    op, in_args, out_args = get_op_data(code, compustate.pc)
    # empty stack error
    if in_args > len(compustate.stack):
        return []
    # out of gas error
    fee = calcfee(block, tx, msg, compustate, op)
    if fee > compustate.gas:
        if debug:
            print("Out of gas", compustate.gas, "need", fee)
            print(op, list(reversed(compustate.stack)))
        return OUT_OF_GAS
    stackargs = []
    for i in range(in_args):
        stackargs.append(compustate.stack.pop())
    if debug:
        import serpent
        if op[:4] == 'PUSH':
            start, n = compustate.pc + 1, int(op[4:])
            print(op, utils.big_endian_to_int(code[start:start + n]))
        else:
            print(op, ' '.join(map(str, stackargs)),
                  serpent.decode_datalist(compustate.memory))
    # Apply operation
    oldgas = compustate.gas
    oldpc = compustate.pc
    compustate.gas -= fee
    compustate.pc += 1
    stk = compustate.stack
    mem = compustate.memory
    if op == 'STOP':
        return []
    elif op == 'ADD':
        stk.append((stackargs[0] + stackargs[1]) % 2 ** 256)
    elif op == 'SUB':
        stk.append((stackargs[0] - stackargs[1]) % 2 ** 256)
    elif op == 'MUL':
        stk.append((stackargs[0] * stackargs[1]) % 2 ** 256)
    elif op == 'DIV':
        if stackargs[1] == 0:
            return []
        stk.append(stackargs[0] / stackargs[1])
    elif op == 'MOD':
        if stackargs[1] == 0:
            return []
        stk.append(stackargs[0] % stackargs[1])
    elif op == 'SDIV':
        if stackargs[1] == 0:
            return []
        if stackargs[0] >= 2 ** 255:
            stackargs[0] -= 2 ** 256
        if stackargs[1] >= 2 ** 255:
            stackargs[1] -= 2 ** 256
        stk.append((stackargs[0] / stackargs[1]) % 2 ** 256)
    elif op == 'SMOD':
        if stackargs[1] == 0:
            return []
        if stackargs[0] >= 2 ** 255:
            stackargs[0] -= 2 ** 256
        if stackargs[1] >= 2 ** 255:
            stackargs[1] -= 2 ** 256
        stk.append((stackargs[0] % stackargs[1]) % 2 ** 256)
    elif op == 'EXP':
        stk.append(pow(stackargs[0], stackargs[1], 2 ** 256))
    elif op == 'NEG':
        stk.append(2 ** 256 - stackargs[0])
    elif op == 'LT':
        stk.append(1 if stackargs[0] < stackargs[1] else 0)
    elif op == 'GT':
        stk.append(1 if stackargs[0] > stackargs[1] else 0)
    elif op == 'SLT':
        if stackargs[0] >= 2 ** 255:
            stackargs[0] -= 2 ** 256
        if stackargs[1] >= 2 ** 255:
            stackargs[1] -= 2 ** 256
        stk.append(1 if stackargs[0] < stackargs[1] else 0)
    elif op == 'SGT':
        if stackargs[0] >= 2 ** 255:
            stackargs[0] -= 2 ** 256
        if stackargs[1] >= 2 ** 255:
            stackargs[1] -= 2 ** 256
        stk.append(1 if stackargs[0] > stackargs[1] else 0)
    elif op == 'EQ':
        stk.append(1 if stackargs[0] == stackargs[1] else 0)
    elif op == 'NOT':
        stk.append(0 if stackargs[0] else 1)
    elif op == 'AND':
        stk.append(stackargs[0] & stackargs[1])
    elif op == 'OR':
        stk.append(stackargs[0] | stackargs[1])
    elif op == 'XOR':
        stk.append(stackargs[0] ^ stackargs[1])
    elif op == 'BYTE':
        if stackargs[0] >= 32:
            stk.append(0)
        else:
            stk.append((stackargs[1] / 256 ** stackargs[0]) % 256)
    elif op == 'SHA3':
        if len(mem) < ceil32(stackargs[0] + stackargs[1]):
            mem.extend([0] * (ceil32(stackargs[0] + stackargs[1]) - len(mem)))
        data = ''.join(map(chr, mem[stackargs[0]:stackargs[0] + stackargs[1]]))
        print 'data time!'
        print data
        print data.encode('hex')
        stk.append(int(utils.sha3(data).encode('hex'), 16))
    elif op == 'ECVERIFY':
        # parameters: msg_hash (32), v (32), r (32), s (32), pubX (32), pubY (32)
        # stack should have all args
        msg_hash, v, r, s, pubX, pubY = stackargs
        pubX = utils.int_to_big_endian(pubX).encode('hex')
        pubY = utils.int_to_big_endian(pubY).encode('hex')
        msg_hash = utils.int_to_big_endian(msg_hash)
        pub = ('04' + pubX + pubY).decode('hex')
        verified = ecdsa_raw_verify(msg_hash, (v, r, s), pub)
        print 'verified: ', verified
        stk.append(verified)
    elif op == 'ECRECOVER':
        # parameters: msg_hash (32), v (32), r (32), s (32), p (64 - empty array to hold pubkey)
        # stack should have all args
        msg_hash, v, r, s = stackargs
        msg_hash = utils.int_to_big_endian(msg_hash)
        pubX, pubY = ecdsa_raw_recover(msg_hash, (v, r, s))
        stk.append(pubX)
        stk.append(pubY)
    elif op == 'PUB2ADDR':
        pubX, pubY = stackargs
        pubX = utils.int_to_big_endian(pubX).encode('hex')
        pubY = utils.int_to_big_endian(pubY).encode('hex')
        pub = pubX + pubY
        pub = pub.decode('hex')
        addr = utils.sha3(pub)[12:]
        stk.append(addr)
    elif op == 'ADDRESS':
        stk.append(msg.to)
    elif op == 'BALANCE':
        stk.append(block.get_balance(msg.to))
    elif op == 'ORIGIN':
        stk.append(tx.sender)
    elif op == 'CALLER':
        stk.append(utils.coerce_to_int(msg.sender))
    elif op == 'CALLVALUE':
        stk.append(msg.value)
    elif op == 'CALLDATALOAD':
        if stackargs[0] >= len(msg.data):
            stk.append(0)
        else:
            dat = msg.data[stackargs[0]:stackargs[0] + 32]
            stk.append(utils.big_endian_to_int(dat + '\x00' * (32 - len(dat))))
    elif op == 'CALLDATASIZE':
        stk.append(len(msg.data))
    elif op == 'CALLDATACOPY':
        if len(mem) < ceil32(stackargs[1] + stackargs[2]):
            mem.extend([0] * (ceil32(stackargs[1] + stackargs[2]) - len(mem)))
        for i in range(stackargs[2]):
            if stackargs[0] + i < len(msg.data):
                mem[stackargs[1] + i] = ord(msg.data[stackargs[0] + i])
            else:
                mem[stackargs[1] + i] = 0
    elif op == 'GASPRICE':
        stk.append(tx.gasprice)
    elif op == 'CODECOPY':
        if len(mem) < ceil32(stackargs[1] + stackargs[2]):
            mem.extend([0] * (ceil32(stackargs[1] + stackargs[2]) - len(mem)))
        for i in range(stackargs[2]):
            if stackargs[0] + i < len(code):
                mem[stackargs[1] + i] = ord(code[stackargs[0] + i])
            else:
                mem[stackargs[1] + i] = 0
    elif op == 'PREVHASH':
        stk.append(utils.big_endian_to_int(block.prevhash))
    elif op == 'COINBASE':
        stk.append(utils.big_endian_to_int(block.coinbase.decode('hex')))
    elif op == 'TIMESTAMP':
        stk.append(block.timestamp)
    elif op == 'NUMBER':
        stk.append(block.number)
    elif op == 'DIFFICULTY':
        stk.append(block.difficulty)
    elif op == 'GASLIMIT':
        stk.append(block.gaslimit)
    elif op == 'POP':
        pass
    elif op == 'DUP':
        stk.append(stackargs[0])
        stk.append(stackargs[0])
    elif op == 'SWAP':
        stk.append(stackargs[0])
        stk.append(stackargs[1])
    elif op == 'MLOAD':
        if len(mem) < ceil32(stackargs[0] + 32):
            mem.extend([0] * (ceil32(stackargs[0] + 32) - len(mem)))
        data = ''.join(map(chr, mem[stackargs[0]:stackargs[0] + 32]))
        stk.append(utils.big_endian_to_int(data))
    elif op == 'MSTORE':
        if len(mem) < ceil32(stackargs[0] + 32):
            mem.extend([0] * (ceil32(stackargs[0] + 32) - len(mem)))
        v = stackargs[1]
        #if isinstance(v, str):
        #    v = int(v.encode('hex'), 16)
        for i in range(31, -1, -1):
            mem[stackargs[0] + i] = v % 256
            v /= 256
    elif op == 'MSTORE8':
        if len(mem) < ceil32(stackargs[0] + 1):
            mem.extend([0] * (ceil32(stackargs[0] + 1) - len(mem)))
        mem[stackargs[0]] = stackargs[1] % 256
    elif op == 'SLOAD':
        stk.append(block.get_storage_data(msg.to, stackargs[0]))
    elif op == 'SSTORE':
        block.set_storage_data(msg.to, stackargs[0], stackargs[1])
    elif op == 'JUMP':
        compustate.pc = stackargs[0]
    elif op == 'JUMPI':
        if stackargs[1]:
            compustate.pc = stackargs[0]
    elif op == 'PC':
        stk.append(compustate.pc)
    elif op == 'MSIZE':
        stk.append(len(mem))
    elif op == 'GAS':
        stk.append(oldgas)
    elif op[:4] == 'PUSH':
        pushnum = int(op[4:])
        compustate.pc = oldpc + 1 + pushnum
        dat = code[oldpc + 1: oldpc + 1 + pushnum]
        stk.append(utils.big_endian_to_int(dat))
    elif op == 'CREATE':
        if len(mem) < ceil32(stackargs[2] + stackargs[3]):
            mem.extend([0] * (ceil32(stackargs[2] + stackargs[3]) - len(mem)))
        gas = stackargs[0]
        value = stackargs[1]
        data = ''.join(map(chr, mem[stackargs[2]:stackargs[2] + stackargs[3]]))
        if debug:
            print("Sub-contract:", msg.to, value, gas, data)
        addr, gas, code = create_contract(
            block, tx, Message(msg.to, '', value, gas, data))
        if debug:
            print("Output of contract creation:", addr, code)
        if addr:
            stk.append(utils.coerce_to_int(addr))
        else:
            stk.append(0)
    elif op == 'CALL':
        if len(mem) < ceil32(stackargs[3] + stackargs[4]):
            mem.extend([0] * (ceil32(stackargs[3] + stackargs[4]) - len(mem)))
        if len(mem) < ceil32(stackargs[5] + stackargs[6]):
            mem.extend([0] * (ceil32(stackargs[5] + stackargs[6]) - len(mem)))
        gas = stackargs[0]
        to = utils.encode_int(stackargs[1])
        to = (('\x00' * (32 - len(to))) + to)[12:]
        value = stackargs[2]
        data = ''.join(map(chr, mem[stackargs[3]:stackargs[3] + stackargs[4]]))
        if debug:
            print("Sub-call:", utils.coerce_addr_to_hex(msg.to),
                  utils.coerce_addr_to_hex(to), value, gas, data)
        result, gas, data = apply_msg(
            block, tx, Message(msg.to, to, value, gas, data))
        if debug:
            print("Output of sub-call:", result, data, "length", len(data),
                  "expected", stackargs[6])
        for i in range(stackargs[6]):
            mem[stackargs[5] + i] = 0
        if result == 0:
            stk.append(0)
        else:
            stk.append(1)
            compustate.gas += gas
            for i in range(len(data)):
                mem[stackargs[5] + i] = data[i]
    elif op == 'RETURN':
        if len(mem) < ceil32(stackargs[0] + stackargs[1]):
            mem.extend([0] * (ceil32(stackargs[0] + stackargs[1]) - len(mem)))
        return mem[stackargs[0]:stackargs[0] + stackargs[1]]
    elif op == 'SUICIDE':
        to = utils.encode_int(stackargs[0])
        to = (('\x00' * (32 - len(to))) + to)[12:]
        block.delta_balance(to, block.get_balance(msg.to))
        block.state.update(msg.to, '')
        return []