def _derive_and_print(master_key: str,
                      *path: int,
                      derive_pub_key: bool = True,
                      magicbyte: int = 0):
    master_pub_key = bitcoin.bip32_privtopub(master_key)
    derived_key = _derived_key(master_key, *path)
    if derive_pub_key:
        derived_bip32_pub_key = _derived_key(master_pub_key, *path)
        derived_pub_key = bitcoin.bip32_extract_key(derived_bip32_pub_key)
    else:
        derived_bip32_pub_key = derived_pub_key = 'N.A.'
    derived_pub_key_from_key = bitcoin.bip32_privtopub(derived_key)
    print('''    Derivation path: ({}),
    Derived BIP32 key: {},
    Derived BIP32 public key: {},
    BIP32 public key from derived BIP32 private: {},
    Derived key: {},
    Derived public key: {},
    Public key from derived key: {},
    BTC address: {}
    '''.format(
        ', '.join(
            str(x) if x <= 2**31 else str(x - 2**31) + '\'' for x in path),
        derived_key, derived_bip32_pub_key, derived_pub_key_from_key,
        bitcoin.bip32_extract_key(derived_key), derived_pub_key,
        bitcoin.privtopub(bitcoin.bip32_extract_key(derived_key)),
        bitcoin.pubtoaddr(bitcoin.privtopub(
            bitcoin.bip32_extract_key(derived_key)),
                          magicbyte=magicbyte)))
Esempio n. 2
0
    def test_finalize_gas(self):
        r_priv = tester.keys[9]
        r_pub = bitcoin.privtopub(r_priv)
        r_addr = tester.accounts[9]
        p_priv = tester.keys[2]
        p_pub = bitcoin.privtopub(p_priv)
        p_addr = tester.accounts[2]
        swap_contract_addr, _ = self.deploy_swap(p_addr)
        random.seed(0)
        kdf_seed = random.getrandbits(32 * 8)
        i = random.randint(1, 100)

        def cpack(n, bts):
            import struct
            fmt = "!{}B".format(n)
            return struct.pack(
                fmt, *[bts >> i & 0xff for i in reversed(range(0, n * 8, 8))])

        # secret represents partial evaluation of KDF derivation function
        # where KDF(kdf_seed, i) = sha3(kdf_seed ++ i)
        secret = cpack(30, kdf_seed) + cpack(2, i)
        assert len(secret) == 32
        value = random.randint(1, 1000000000)
        # in Solidity: sha3(sha3(secret), bytes32(_value)):
        msghash = utils.sha3(utils.sha3(secret) + cpack(32, value))
        (V, R, S) = sign_btc(msghash, r_priv, r_pub)
        assert (V, R, S) == sign_eth(msghash, r_priv)
        ER = cpack(32, R)
        ES = cpack(32, S)
        self.s.finalize(secret, value, ER, ES, V, sender=p_priv)
Esempio n. 3
0
def generate_keyfiles(n, m, vf, sf):
    '''Generate a set of public and private keys
    for testing.
    n - the number of OR loops
    m - the number of keys per loop (note: constant in this crude version)
    vf - the file path to which to write the verification keys
    sf - the file path to which to write the signing (private) keys
    '''
    signing_indices = [random.choice(range(m)) for _ in range(n)]
    priv = []
    with open(sf, 'wb') as f:
        for i in range(n):
            priv.append(os.urandom(32))
            f.write(binascii.hexlify(priv[i]) + '\n')
    with open(vf, 'wb') as f:
        for i in range(n):
            pubkeys = []
            for j in range(m):
                if j == signing_indices[i]:
                    p = btc.privtopub(priv[i])
                else:
                    p = btc.privtopub(os.urandom(32))
                p = btc.decode_pubkey(p)
                p = btc.encode_pubkey(p, 'bin_compressed')
                pubkeys.append(binascii.hexlify(p))
            f.write(','.join(pubkeys) + '\n')
Esempio n. 4
0
def generate_keyfiles(n, m, vf, sf):
    '''Generate a set of public and private keys
    for testing.
    n - the number of OR loops
    m - the number of keys per loop (note: constant in this crude version)
    vf - the file path to which to write the verification keys
    sf - the file path to which to write the signing (private) keys
    '''
    signing_indices = [random.choice(range(m)) for _ in range(n)]
    priv=[]
    with open(sf,'wb') as f:
	for i in range(n):
	    priv.append(os.urandom(32))
	    f.write(binascii.hexlify(priv[i])+'\n')    
    with open(vf,'wb') as f:
	for i in range(n):
	    pubkeys = []
	    for j in range(m):
		if j==signing_indices[i]:
		    p = btc.privtopub(priv[i])
		else:
		    p = btc.privtopub(os.urandom(32))
		p = btc.decode_pubkey(p)
		p = btc.encode_pubkey(p,'bin_compressed')
		pubkeys.append(binascii.hexlify(p))
	    f.write(','.join(pubkeys)+'\n')
Esempio n. 5
0
def sign_tx(private_key, hex_data):
	public_address = pubtoaddr(privtopub(private_key))
	pubkey = privtopub(private_key)
	split_data = hex_data.split("00ffffffff")
	input_stubs = split_data[:-1]
	output_stub = split_data[-1]
	pre_sig_script = '1976a914'+b58check_to_hex(public_address)+'88acffffffff'
	sig_stubs = []
	for i in range(len(input_stubs)):
		signing_message = ''
		for j in range(i):
			signing_message += input_stubs[j]+'00ffffffff'
		signing_message += input_stubs[i] + pre_sig_script
		for k in range(i+1, len(input_stubs)):
			signing_message += input_stubs[k]+'00ffffffff'
		signing_message += output_stub+'01000000'
		hashed_message = hashlib.sha256(hashlib.sha256(signing_message.decode('hex')).digest()).digest()
		signingkey = ecdsa.SigningKey.from_string(b58check_to_hex(private_key).decode('hex'), curve=ecdsa.SECP256k1)
		SIG = binascii.hexlify(signingkey.sign_digest(hashed_message, sigencode=ecdsa.util.sigencode_der_canonize))
		ScriptSig = hex(len(SIG+'01')/2)[2:] + SIG + '01' + hex(len(pubkey)/2)[2:] + pubkey	
		ScriptLength = hex(len(ScriptSig)/2)[2:]
		sig_stub = ScriptLength+ScriptSig+'ffffffff'
		sig_stubs.append(sig_stub)
	bytes_ = ''
	for q in range(len(sig_stubs)):
		bytes_ += input_stubs[q]+sig_stubs[q]
	bytes_ += output_stub
	return bytes_
Esempio n. 6
0
def ringsig_sign_substitute(msghash, priv, pub_xs, pub_ys):
    # Number of pubkeys
    n = len(pub_xs)
    # Create list of pubkeys as (x, y) points
    pubs = [(pub_xs[i], recover_y(pub_xs[i], bit(pub_ys, i)))
            for i in range(n)]
    # My pubkey
    my_pub = b.decode_pubkey(b.privtopub(priv))
    # Compute my index in the pubkey list
    my_index = 0
    while my_index < n:
        if pubs[my_index] == my_pub:
            break
        my_index += 1
    assert my_index < n
    # Compute the signer's I value
    I = b.multiply(hash_to_pubkey(list(my_pub)), priv)
    # Select a random ephemeral key
    k = b.hash_to_int(b.random_key())
    # Store the list of intermediate values in the "ring"
    e = [None] * n
    # Compute the entry in the ring corresponding to the signer's index
    kpub = b.privtopub(k)
    kmulpub = b.multiply(hash_to_pubkey(list(my_pub)), k)
    orig_left = hash_array([msghash, kpub[0], kpub[1], kmulpub[0], kmulpub[1]])
    orig_right = hash_value(orig_left)
    e[my_index] = {"left": orig_left, "right": orig_right}
    # Map of intermediate s values (part of the signature)
    s = [None] * n
    for i in list(range(my_index + 1, n)) + list(range(my_index + 1)):
        prev_i = (i - 1) % n
        # In your position in the ring, set the s value based on your private
        # knowledge of k; this lets you "invert" the hash function in order to
        # ensure a consistent ring. At all other positions, select a random s
        if i == my_index:
            s[prev_i] = b.add_privkeys(
                k, b.mul_privkeys(e[prev_i]["right"], priv))
        else:
            s[prev_i] = b.hash_to_int(b.random_key())
        # Create the next values in the ring based on the chosen s value
        pub1 = b.subtract_pubkeys(b.privtopub(s[prev_i]),
                                  b.multiply(pubs[i], e[prev_i]["right"]))
        pub2 = b.subtract_pubkeys(
            b.multiply(hash_to_pubkey(list(pubs[i])), s[prev_i]),
            b.multiply(I, e[prev_i]["right"]))
        left = hash_array([msghash, pub1[0], pub1[1], pub2[0], pub2[1]])
        right = hash_value(left)
        e[i] = {"left": left, "right": right}
    # Check that the ring is consistent
    assert (left, right) == (orig_left, orig_right)
    # Return the first value in the ring, the s values, and the signer's
    # I value in compressed form
    return (e[0]["left"], s, I[0], I[1] % 2)
Esempio n. 7
0
 def test_native_P2WSH_SIGHASH_SINGLE(self):
     tx = TEST_CASES[1]
     deserialized = deserialize(tx['unsigned'])
     serialized = serialize(deserialized)
     self.assertEqual(serialized, tx['unsigned'])
     self.assertEqual(deserialized['locktime'], tx['locktime'])
     ins = self.get_pybtc_vins(tx)
     outs = self.get_pybtc_outs(tx)
     generated_tx = mktx(ins, outs)
     stripped_tx = strip_witness_data(generated_tx)
     self.assertEqual(stripped_tx, serialized)
     partially_signed = p2pk_sign(stripped_tx,
                                  0,
                                  self.append_compressed_flag_to_privkey(
                                      tx['ins'][0]['privkey']),
                                  hashcode=SIGHASH_ALL)
     priv0 = self.append_compressed_flag_to_privkey(
         tx['ins'][1]['privkeys'][0])
     priv1 = self.append_compressed_flag_to_privkey(
         tx['ins'][1]['privkeys'][1])
     pub0 = privtopub(priv0)
     pub1 = privtopub(priv1)
     REDEEM_SCRIPT_STRUCTURE = {
         'keys': [pub0, pub1],
         'schema': [{
             'reqs': 1,
             'keys': [0],
         }, {
             'reqs': 1,
             'keys': [1],
         }]
     }
     witness_script = mk_OPCS_multisig_script(REDEEM_SCRIPT_STRUCTURE)
     sign1 = segwit_multisign(partially_signed,
                              1,
                              witness_script,
                              priv0,
                              49 * 10**8,
                              hashcode=SIGHASH_SINGLE)
     sign2 = segwit_multisign(partially_signed,
                              1,
                              witness_script,
                              priv1,
                              49 * 10**8,
                              hashcode=SIGHASH_SINGLE,
                              separator_index=1)
     signed = apply_segwit_multisignatures(partially_signed,
                                           1,
                                           witness_script, [sign2, sign1],
                                           dummy=False)
     self.assertEqual(signed, tx['signed'])
     print('[Native P2WSH] SIGHASH_SINGLE OK')
Esempio n. 8
0
 def test_native_P2WSH_SIGHASH_SINGLE(self):
     tx = TEST_CASES[1]
     deserialized = deserialize(tx['unsigned'])
     serialized = serialize(deserialized)
     self.assertEqual(serialized, tx['unsigned'])
     self.assertEqual(deserialized['locktime'], tx['locktime'])
     ins = self.get_pybtc_vins(tx)
     outs = self.get_pybtc_outs(tx)
     generated_tx = mktx(ins, outs)
     stripped_tx = strip_witness_data(generated_tx)
     self.assertEqual(stripped_tx, serialized)
     partially_signed = p2pk_sign(stripped_tx,
                                  0,
                                  self.append_compressed_flag_to_privkey(tx['ins'][0]['privkey']),
                                  hashcode=SIGHASH_ALL)
     priv0 = self.append_compressed_flag_to_privkey(tx['ins'][1]['privkeys'][0])
     priv1 = self.append_compressed_flag_to_privkey(tx['ins'][1]['privkeys'][1])
     pub0 = privtopub(priv0)
     pub1 = privtopub(priv1)
     REDEEM_SCRIPT_STRUCTURE = {
         'keys': [
             pub0,
             pub1
         ],
         'schema': [
             {
                 'reqs': 1,
                 'keys': [0],
             },
             {
                 'reqs': 1,
                 'keys': [1],
             }
         ]
     }
     witness_script = mk_OPCS_multisig_script(REDEEM_SCRIPT_STRUCTURE)
     sign1 = segwit_multisign(partially_signed,
                              1,
                              witness_script,
                              priv0,
                              49 * 10**8,
                              hashcode=SIGHASH_SINGLE)
     sign2 = segwit_multisign(partially_signed,
                              1,
                              witness_script,
                              priv1,
                              49 * 10 ** 8,
                              hashcode=SIGHASH_SINGLE,
                              separator_index=1)
     signed = apply_segwit_multisignatures(partially_signed, 1, witness_script, [sign2, sign1], dummy=False)
     self.assertEqual(signed, tx['signed'])
     print('[Native P2WSH] SIGHASH_SINGLE OK')
Esempio n. 9
0
def test_key():
    priv, pub = gen_key_pair()
    assert pub == privtopub(priv)
    priv, pub = gen_key_pair()
    assert pub == privtopub(priv)

    priv, pub = gen_key_pair()
    assert pub == privtopub(priv)

    priv, pub = gen_key_pair()
    assert pub == privtopub(priv)

    priv, pub = gen_key_pair()
    assert pub == privtopub(priv)
Esempio n. 10
0
def ringsig_sign_substitute(msghash, priv, pub_xs, pub_ys):
    # Number of pubkeys
    n = len(pub_xs)
    # Create list of pubkeys as (x, y) points
    pubs = [(pub_xs[i], recover_y(pub_xs[i], bit(pub_ys, i))) for i in range(n)]
    # My pubkey
    my_pub = b.decode_pubkey(b.privtopub(priv))
    # Compute my index in the pubkey list
    my_index = 0
    while my_index < n:
        if pubs[my_index] == my_pub:
            break
        my_index += 1
    assert my_index < n
    # Compute the signer's I value
    I = b.multiply(hash_to_pubkey(list(my_pub)), priv)
    # Select a random ephemeral key
    k = b.hash_to_int(b.random_key())
    # Store the list of intermediate values in the "ring"
    e = [None] * n
    # Compute the entry in the ring corresponding to the signer's index
    kpub = b.privtopub(k)
    kmulpub = b.multiply(hash_to_pubkey(list(my_pub)), k)
    orig_left = hash_array([msghash, kpub[0], kpub[1], kmulpub[0], kmulpub[1]])
    orig_right = hash_value(orig_left)
    e[my_index] = {"left": orig_left, "right": orig_right}
    # Map of intermediate s values (part of the signature)
    s = [None] * n
    for i in list(range(my_index + 1, n)) + list(range(my_index + 1)):
        prev_i = (i - 1) % n
        # In your position in the ring, set the s value based on your private
        # knowledge of k; this lets you "invert" the hash function in order to
        # ensure a consistent ring. At all other positions, select a random s
        if i == my_index:
            s[prev_i] = b.add_privkeys(k, b.mul_privkeys(e[prev_i]["right"], priv))
        else:
            s[prev_i] = b.hash_to_int(b.random_key())
        # Create the next values in the ring based on the chosen s value
        pub1 = b.subtract_pubkeys(b.privtopub(s[prev_i]),
                                  b.multiply(pubs[i], e[prev_i]["right"]))
        pub2 = b.subtract_pubkeys(b.multiply(hash_to_pubkey(list(pubs[i])), s[prev_i]),
                                  b.multiply(I, e[prev_i]["right"]))
        left = hash_array([msghash, pub1[0], pub1[1], pub2[0], pub2[1]])
        right = hash_value(left)
        e[i] = {"left": left, "right": right}
    # Check that the ring is consistent
    assert (left, right) == (orig_left, orig_right)
    # Return the first value in the ring, the s values, and the signer's
    # I value in compressed form
    return (e[0]["left"], s, I[0], I[1] % 2)
Esempio n. 11
0
 def _bake(self):
     self.privates = [
         hashlib.sha256('priv{}'.format(i).encode()).hexdigest() + '01'
         for i in range(0, 18)
     ]
     self._scripts = [
         bitcoin.mk_multisig_script(bitcoin.privtopub(self.privates[x]),
                                    bitcoin.privtopub(self.privates[x + 1]),
                                    bitcoin.privtopub(self.privates[x + 2]),
                                    2) for x in range(0, 18, 3)
     ]
     self.addresses = [
         bitcoin.p2sh_scriptaddr(script, magicbyte=196)
         for script in self._scripts
     ]
def create_key(crypto):
    private_key = bitcoin.random_key()
    public_key  = bitcoin.privtopub(private_key)    
    c.execute('INSERT INTO crypto_key (crypto,public_key,private_key,encrypted_private_key,timestamp) VALUES(?,?,?,?,?)',
        (crypto,public_key,private_key,0,datetime.datetime.now()))
    conn.commit()
    return public_key
Esempio n. 13
0
    def get_next_public_key(  ):
        settings = Settings.Instance().get_settings_json()

        if( settings['bip32master'] is None ):
            raise RuntimeError( "Master key has not been set up yet" )

        account_number, account_key, key_number = KeyHelper.get_account_number_and_chain( settings )

        return_key = bitcoin.bip32_ckd( account_key, key_number )
        return_key = bitcoin.bip32_extract_key( return_key )
        return_key = bitcoin.privtopub( return_key )

        #save key for later
        if 'keys' not in settings['accounts'][account_number]:
            settings['accounts'][account_number]['keys'] = []
        settings['accounts'][account_number]['keys'].append( (key_number, return_key, False ) )
        
        #we increment the key counter after making the key
        #because the chain code is 0 indexed, making the 0th key 
        #the first one we use
        key_number += 1

        #remember to save our new key
        settings['accounts'][account_number]['numKeys'] = key_number
        Settings.Instance().save_config_file( settings )

        return return_key
Esempio n. 14
0
    def get_bip32_key( public_keys ):
        settings = Settings.Instance().get_settings_json()

        if( settings['bip32master'] is None ):
            return None

        account_number, account_key, key_number = KeyHelper.get_account_number_and_chain( settings )

        #see if we already have this cached, and I can just get the key fast
        cached = set( settings['accounts'][account_number].get(keys,[]) )
        pub_set = set( public_keys )
        hits = cached & pub_set 

        if len(hits) > 0:
            return KeyHelper.get_private_for_chain( account_number, hits[0][0], settings )

        #drat, didn't find it! at least we can only need to test the ones that 
        #we didn't already check
        missed = set(range(key_number)) - set([cache[0] for cache in cached])
            
        for i in missed:
            priv = bitcoin.bip32_ckd( account_key, i )
            priv = bitcoin.bip32_extract_key( priv )
            canidate = bitcoin.privtopub( priv )
            if( canidate in public_keys ):
                return priv

        return None
Esempio n. 15
0
	def pushPayment(self):
		#compliantScript = bitcoin.mk_multisig_script([bitcoin.privtopub(self.privS), self.pubKeyClient], 2,2)  # inversion!!!!
		compliantScript = bitcoin.mk_multisig_script([self.pubKeyClient, bitcoin.privtopub(self.privS)], 2,2)
		sigServer = bitcoin.multisign(self.lastpayment, 0, compliantScript, self.privS)
		signedPtx = bitcoin.apply_multisignatures(self.lastpayment, 0, compliantScript, [self.lastsig, sigServer])
		print 'Broadcast the very last payment. Just got richer. Tx hash:', bitcoin.txhash(signedPtx)
		bitcoin.pushtx(signedPtx)
Esempio n. 16
0
def perf(rounds=1000):
    privkeys = [rand32bytes() for i in range(rounds)]
    messages = [rand32bytes() for i in range(rounds)]
    # test sign
    signatures = []
    st = time.time()
    for priv, msg in zip(privkeys, messages):
        s = c_ecdsa_sign_compact(msg32, priv)
        signatures.append(s)
    elapsed = time.time() - st
    print 'cffi took: %.2fsecs / %dμs per op  / %d signs per sec' % \
        (elapsed, elapsed / rounds * 10**6, rounds / elapsed)

    # test recover
    pubs = []
    st = time.time()
    for sig, msg in zip(signatures, messages):
        p = c_ecdsa_recover_compact(msg32, sig)
        pubs.append(p)
    elapsed = time.time() - st
    print 'cffi took: %.2fsecs / %dμs per op  / %d recovers per sec' % \
        (elapsed, elapsed / rounds * 10**6, rounds / elapsed)

    # check
    for pub, privkey in zip(pubs, privkeys)[:100]:
        assert privtopub(privkey) == pub
Esempio n. 17
0
def cosign(master_xpriv, recovery_package):
    raw_txs = recovery_package['txs']
    print "Signing %d transactions" % len(raw_txs)
    for tx_index, tx_raw in enumerate(raw_txs):
        print "\nTransaction #", tx_index
        hex_tx = tx_raw['bytes']
        tx = bitcoin.transaction.deserialize(unhexlify(hex_tx))
        keypaths = tx_raw['input_paths']
        keypairs = {}
        for p in keypaths:
            xpriv = seedlib.bip32_child(master_xpriv, p)
            priv = bitcoin.bip32_extract_key(xpriv)
            pub = bitcoin.privtopub(priv)
            keypairs[pub] = priv
        for i, inp in enumerate(tx['ins']):
            (sigs, pubkeys, redeemScript, M,
             N) = multisig.decode_multisig_script(inp['script'])
            for p in pubkeys:
                if p in keypairs:
                    sig_new = bitcoin.multisign(hex_tx, i, redeemScript,
                                                keypairs[p])
                    sigs.append(sig_new)
                    tx_new = bitcoin.apply_multisignatures(
                        unhexlify(hex_tx), i, redeemScript, sigs)
                    print "Signed transaction %d input %d" % (tx_index, i)

                    # replace tx with newly signed transaction
                    hex_tx = hexlify(tx_new)
        recovery_package['txs'][tx_index]['bytes'] = hex_tx
    return recovery_package
Esempio n. 18
0
 def regenerate_keys(account_key, needed_keys, key_list):
     for key in needed_keys:
         return_key = bitcoin.bip32_ckd(account_key, key)
         return_key = bitcoin.bip32_extract_key(return_key)
         return_key = bitcoin.privtopub(return_key)
         key_list.append((key, return_key, False))
     return
Esempio n. 19
0
    def get_next_public_key():
        settings = Settings.Instance().get_settings_json()

        if (settings['bip32master'] is None):
            raise RuntimeError("Master key has not been set up yet")

        account_number, account_key, key_number = KeyHelper.get_account_number_and_chain(
            settings)

        return_key = bitcoin.bip32_ckd(account_key, key_number)
        return_key = bitcoin.bip32_extract_key(return_key)
        return_key = bitcoin.privtopub(return_key)

        #save key for later
        if 'keys' not in settings['accounts'][account_number]:
            settings['accounts'][account_number]['keys'] = []
        settings['accounts'][account_number]['keys'].append(
            (key_number, return_key, False))

        #we increment the key counter after making the key
        #because the chain code is 0 indexed, making the 0th key
        #the first one we use
        key_number += 1

        #remember to save our new key
        settings['accounts'][account_number]['numKeys'] = key_number
        Settings.Instance().save_config_file(settings)

        return return_key
Esempio n. 20
0
def generate_keypair(crypto, seed, password=None):
    """
    Generate a private key and publickey for any currency, given a seed.
    That seed can be random, or a brainwallet phrase.
    """
    pub_byte, priv_byte = get_magic_bytes(crypto)
    priv = sha256(seed)
    pub = privtopub(priv)

    priv_wif = encode_privkey(priv, 'wif_compressed', vbyte=priv_byte)
    if password:
        # pycrypto etc. must be installed or this will raise ImportError, hence inline import.
        from .bip38 import Bip38EncryptedPrivateKey
        priv_wif = str(Bip38EncryptedPrivateKey.encrypt(crypto, priv_wif, password))

    compressed_pub = encode_pubkey(pub, 'hex_compressed')
    ret = {
        'public': {
            'hex_uncompressed': pub,
            'hex': compressed_pub,
            'address': pubtoaddr(compressed_pub, pub_byte)
        },
        'private': {
            'wif': priv_wif
        }
    }
    if not password:
        # only these are valid when no bip38 password is supplied
        ret['private']['hex'] = encode_privkey(priv, 'hex_compressed', vbyte=priv_byte)
        ret['private']['hex_uncompressed'] = encode_privkey(priv, 'hex', vbyte=priv_byte)
        ret['private']['wif_uncompressed'] = encode_privkey(priv, 'wif', vbyte=priv_byte)

    return ret
Esempio n. 21
0
    def prestart(self):
        super().prestart()

        # geth is locked to user home
        home = os.path.expanduser("~")
        dagfile = os.path.join(home, '.ethash', 'full-R23-0000000000000000')
        if not os.path.exists(dagfile):
            raise Exception("Missing DAG {}. run {} makedag 0 {} to initialise ethminer before tests can be run".format(
                dagfile, self.geth_server, os.path.join(home, '.ethash')))

        if self.settings['rpcport'] is None:
            self.settings['rpcport'] = get_unused_port()

        if self.settings['node_key'] is None:
            self.settings['node_key'] = "{:0>64}".format(binascii.b2a_hex(os.urandom(32)).decode('ascii'))

        if self.settings['ws'] is not None:
            self.settings['wsport'] = get_unused_port()

        self.public_key = "{:0>128}".format(binascii.b2a_hex(bitcoin.privtopub(binascii.a2b_hex(self.settings['node_key']))[1:]).decode('ascii'))

        # write chain file
        write_chain_file(self.version, self.chainfile, self.author, self.difficulty)

        p = subprocess.Popen([self.geth_server, '--datadir', self.get_data_directory(), 'init', self.chainfile], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        outs, errs = p.communicate(timeout=15)

        with open(os.path.join(self.get_data_directory(), 'keystore', 'UTC--2017-02-06T16-16-34.720321115Z--de3d2d9dd52ea80f7799ef4791063a5458d13913'), 'w') as inf:
            inf.write('''{"address":"de3d2d9dd52ea80f7799ef4791063a5458d13913","crypto":{"cipher":"aes-128-ctr","ciphertext":"8d6528acfb366722d9c98f64435bb151f5671f9e4623e546cc7206382a1d54f7","cipherparams":{"iv":"de95c854face9aa50686370cc47d6025"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":262144,"p":1,"r":8,"salt":"6baa74518f9cc34575c981e027154e9c714b400710478c587043c900a37a89b8"},"mac":"37b6d35ea394b129f07e9a90a09b8cc1356d731590201e84405f4592013b4333"},"id":"ce658bd4-6910-4eef-aa39-b32000c38ccc","version":3}''')
Esempio n. 22
0
    def get_bip32_key(public_keys):
        settings = Settings.Instance().get_settings_json()

        if (settings['bip32master'] is None):
            return None

        account_number, account_key, key_number = KeyHelper.get_account_number_and_chain(
            settings)

        #see if we already have this cached, and I can just get the key fast
        cached = set(settings['accounts'][account_number].get(keys, []))
        pub_set = set(public_keys)
        hits = cached & pub_set

        if len(hits) > 0:
            return KeyHelper.get_private_for_chain(account_number, hits[0][0],
                                                   settings)

        #drat, didn't find it! at least we can only need to test the ones that
        #we didn't already check
        missed = set(range(key_number)) - set([cache[0] for cache in cached])

        for i in missed:
            priv = bitcoin.bip32_ckd(account_key, i)
            priv = bitcoin.bip32_extract_key(priv)
            canidate = bitcoin.privtopub(priv)
            if (canidate in public_keys):
                return priv

        return None
Esempio n. 23
0
    def sign(self, key):
        """Sign this transaction with a private key.

        A potentially already existing signature would be overridden.
        """
        if not is_bitcoin_available() or not is_secp256k1_available():
            raise ImportError(
                "In order to sign transactions the "
                "`bitcoin` and `secp256k1` packages must be installed.")
        from bitcoin import privtopub
        from secp256k1 import PrivateKey

        if key in (0, b'', b'\x00' * 32, b'0' * 64):
            raise ValueError("Zero privkey cannot sign")

        rawhash = decode_hex(sha3(rlp.encode(self, UnsignedTransaction)))

        if len(key) in {64, 66}:
            # we need a binary key
            key = decode_hex(key)

        pk = PrivateKey(key, raw=True)
        sig_bytes, rec_id = pk.ecdsa_recoverable_serialize(
            pk.ecdsa_sign_recoverable(rawhash, raw=True))
        signature = sig_bytes + force_bytes(chr(rec_id))
        self.v = (ord(signature[64])
                  if is_string(signature[64]) else signature[64]) + 27
        self.r = decode_big_endian_int(signature[0:32])
        self.s = decode_big_endian_int(signature[32:64])

        self.sender = to_address(sha3(privtopub(key)[1:])[-40:])
        return self
Esempio n. 24
0
    def sign(self, key):
        """Sign this transaction with a private key.

        A potentially already existing signature would be overridden.
        """
        if not is_bitcoin_available() or not is_secp256k1_available():
            raise ImportError(
                "In order to sign transactions the "
                "`bitcoin` and `secp256k1` packages must be installed."
            )
        from bitcoin import privtopub
        from secp256k1 import PrivateKey

        if key in (0, b'', b'\x00' * 32, b'0' * 64):
            raise ValueError("Zero privkey cannot sign")

        rawhash = decode_hex(sha3(rlp.encode(self, UnsignedTransaction)))

        if len(key) in {64, 66}:
            # we need a binary key
            key = decode_hex(key)

        pk = PrivateKey(key, raw=True)
        sig_bytes, rec_id = pk.ecdsa_recoverable_serialize(
            pk.ecdsa_sign_recoverable(rawhash, raw=True)
        )
        signature = sig_bytes + force_bytes(chr(rec_id))
        self.v = (ord(signature[64]) if is_string(signature[64]) else signature[64]) + 27
        self.r = decode_big_endian_int(signature[0:32])
        self.s = decode_big_endian_int(signature[32:64])

        self.sender = to_address(sha3(privtopub(key)[1:])[-40:])
        return self
Esempio n. 25
0
def generate_keypair(crypto, seed, password=None):
    """
    Generate a private key and publickey for any currency, given a seed.
    That seed can be random, or a brainwallet phrase.
    """
    pub_byte, priv_byte = get_magic_bytes(crypto)
    priv = sha256(seed)
    pub = privtopub(priv)

    if priv_byte >= 128:
        priv_byte -= 128 #pybitcointools bug

    priv_wif = encode_privkey(priv, 'wif_compressed', vbyte=priv_byte)
    if password:
        priv_wif = bip38_encrypt(priv_wif, password)

    compressed_pub = encode_pubkey(pub, 'hex_compressed')
    ret = {
        'public': {
            'hex_uncompressed': pub,
            'hex': compressed_pub,
            'address': pubtoaddr(compressed_pub, pub_byte)
        },
        'private': {
            'wif': priv_wif
        }
    }
    if not password:
        # only these are valid when no bip38 password is supplied
        ret['private']['hex'] = encode_privkey(priv, 'hex_compressed', vbyte=priv_byte)
        ret['private']['hex_uncompressed'] = encode_privkey(priv, 'hex', vbyte=priv_byte)
        ret['private']['wif_uncompressed'] = encode_privkey(priv, 'wif', vbyte=priv_byte)

    return ret
Esempio n. 26
0
def ringsig_verify_substitute(msghash, x0, s, Ix, Iy, pub_xs, pub_ys):
    # Number of pubkeys
    n = len(pub_xs)
    # Create list of pubkeys as (x, y) points
    pubs = [(pub_xs[i], recover_y(pub_xs[i], bit(pub_ys, i))) for i in range(n)]
    # Decompress the provided I value
    I = Ix, recover_y(Ix, Iy)
    # Store the list of intermediate values in the "ring"
    e = [None] * (n + 1)
    # Set the first value in the ring to that provided in the signature
    e[0] = [x0, hash_value(x0)]
    i = 1
    while i < n + 1:
        prev_i = (i - 1) % n
        # Create the next values in the ring based on the provided s value
        pub1 = b.subtract_pubkeys(b.privtopub(s[prev_i]),
                                  b.multiply(pubs[i % n], e[prev_i][1]))
        pub2 = b.subtract_pubkeys(b.multiply(hash_to_pubkey(list(pubs[i % n])), s[prev_i]),
                                  b.multiply(I, e[prev_i][1]))
        left = hash_array([msghash, pub1[0], pub1[1], pub2[0], pub2[1]])
        right = hash_value(left)
        # FOR DEBUGGING
        # if i >= 1:
        #     print 'pre', pubs[i % n]
        #     print 'pub1', pub1
        #     print 'pub2', pub2
        #     print 'left', left
        #     print 'right', right
        e[i] = [left, right]
        i += 1
    # Check that the ring is consistent
    return(e[n][0] == e[0][0] and e[n][1] == e[0][1])
Esempio n. 27
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
Esempio n. 28
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
Esempio n. 29
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
Esempio n. 30
0
def ringsig_verify_substitute(msghash, x0, s, Ix, Iy, pub_xs, pub_ys):
    # Number of pubkeys
    n = len(pub_xs)
    # Create list of pubkeys as (x, y) points
    pubs = [(pub_xs[i], recover_y(pub_xs[i], bit(pub_ys, i)))
            for i in range(n)]
    # Decompress the provided I value
    I = Ix, recover_y(Ix, Iy)
    # Store the list of intermediate values in the "ring"
    e = [None] * (n + 1)
    # Set the first value in the ring to that provided in the signature
    e[0] = [x0, hash_value(x0)]
    i = 1
    while i < n + 1:
        prev_i = (i - 1) % n
        # Create the next values in the ring based on the provided s value
        pub1 = b.subtract_pubkeys(b.privtopub(s[prev_i]),
                                  b.multiply(pubs[i % n], e[prev_i][1]))
        pub2 = b.subtract_pubkeys(
            b.multiply(hash_to_pubkey(list(pubs[i % n])), s[prev_i]),
            b.multiply(I, e[prev_i][1]))
        left = hash_array([msghash, pub1[0], pub1[1], pub2[0], pub2[1]])
        right = hash_value(left)
        # FOR DEBUGGING
        # if i >= 1:
        #     print 'pre', pubs[i % n]
        #     print 'pub1', pub1
        #     print 'pub2', pub2
        #     print 'left', left
        #     print 'right', right
        e[i] = [left, right]
        i += 1
    # Check that the ring is consistent
    return (e[n][0] == e[0][0] and e[n][1] == e[0][1])
Esempio n. 31
0
 def regenerate_keys( account_key, needed_keys, key_list ):
     for key in needed_keys:
         return_key = bitcoin.bip32_ckd(account_key, key)
         return_key = bitcoin.bip32_extract_key(return_key)
         return_key = bitcoin.privtopub(return_key)
         key_list.append( ( key, return_key, False ) )
     return 
Esempio n. 32
0
def test_cccoin_mc_write(mc_node_url, cccoin_core):
    cccoin_core.mcq = MediachainQueue(mc_api_url=mc_node_url,
                                      default_namespace='cccoin')
    the_pw = 'some big long brainwallet password'
    priv = btc.sha256(the_pw)
    pub = btc.privtopub(priv)
    blind_post, unblind_post = client_post(
        'http://foo',
        'The Title ',
        priv,
        pub,
    )

    cccoin_core.submit_blind_action(blind_post)
    cccoin_core.submit_unblind_action(unblind_post)
    cccoin_core.cw.loop_once()
    start_block = cccoin_core.cw.latest_block_num

    while cccoin_core.cw.latest_block_num < start_block + 3:  # not sure why / if this is the magic number, but it WFM...
        cccoin_core.cw.loop_once()
        sleep(0.1)

    cccoin_core.mcq.wait_for_completion()

    client = MediachainClient(mc_api_url=mc_node_url)
    results = IOLoop.current().run_sync(
        lambda: client.query('SELECT * FROM cccoin'))

    assert (len(results) > 0)
Esempio n. 33
0
def perf(rounds=1000):
    privkeys = [rand32bytes() for i in range(rounds)]
    messages = [rand32bytes() for i in range(rounds)]
    # test sign
    signatures = []
    st = time.time()
    for priv, msg in zip(privkeys, messages):
        s = c_ecdsa_sign_compact(msg32, priv)
        signatures.append(s)
    elapsed = time.time() - st
    print 'cffi took: %.2fsecs / %dμs per op  / %d signs per sec' % \
        (elapsed, elapsed / rounds * 10**6, rounds / elapsed)

    # test recover
    pubs = []
    st = time.time()
    for sig, msg in zip(signatures, messages):
        p = c_ecdsa_recover_compact(msg32, sig)
        pubs.append(p)
    elapsed = time.time() - st
    print 'cffi took: %.2fsecs / %dμs per op  / %d recovers per sec' % \
        (elapsed, elapsed / rounds * 10**6, rounds / elapsed)

    # check
    for pub, privkey in zip(pubs, privkeys)[:100]:
        assert privtopub(privkey) == pub
Esempio n. 34
0
def warp(passphrase, salt=""):
    s1 = scrypt.hash(passphrase + "\x01", salt+"\x01", N=2**18, r=8, p=1,
                     buflen=32)
    s2 = pbkdf2(passphrase + "\x02", salt=salt+"\x02", keylen=32, rounds=2**16,
                prf="hmac-sha256")
    key = binascii.hexlify(xor(s1, s2))
    return key, bitcoin.pubtoaddr(bitcoin.privtopub(key))
Esempio n. 35
0
    def save(self, *args, **kwargs):
        created = not self.pk

        if created:
            self.public_key = privtopub(self.private_key)
            self.address = pubtoaddr(self.public_key)

        super().save(*args, **kwargs)
Esempio n. 36
0
 def foo(f):
     result.append(f.result())
     if len(result) == len(futures):
         key = binascii.hexlify(xor(*result))
         pub = bitcoin.pubtoaddr(bitcoin.privtopub(key))
         if pub == _pub_key:
             print "Found passphrase: ", passphrase
             print key , "->", pub
Esempio n. 37
0
 def mine(cls, min_value=1):
     seckey = os.urandom(32)
     while True:
         seckey = utils.sha3(seckey)
         pubkey = utils.sha3(b.privtopub(seckey)[1:])[12:]
         value = 2**difficulty(utils.sha3(pubkey))
         if value >= min_value:
             return cls(pubkey, seckey)
Esempio n. 38
0
 def foo(f):
     result.append(f.result())
     if len(result) == len(futures):
         key = binascii.hexlify(xor(*result))
         pub = bitcoin.pubtoaddr(bitcoin.privtopub(key))
         if pub == _pub_key:
             print "Found passphrase: ", passphrase
             print key, "->", pub
Esempio n. 39
0
    def run(self):
        print 'Initialisation of MPC...'

        # exchange public keys
        pubKeyServer = bitcoin.privtopub(self.privS)
        print 'pubKeyServer: ', pubKeyServer
        self.pubKeyClient = txUtils.exchangePubKey(pubKeyServer, self.c)
        print 30 * '#', 'Handshake', 30 * '#'
        print 'Public Key received from client is: ', self.pubKeyClient

        # receive the signed Dtx and
        signedDtx = self.c.jrecv()
        print 'SignedDtx:', signedDtx
        #print pprint(bitcoin.deserialize(signedDtx))
        scriptDtx = self.c.jrecv()
        print 'ScriptDtx: ', scriptDtx
        own = bitcoin.mk_multisig_script(
            [self.pubKeyClient,
             bitcoin.privtopub(self.privS)], 2, 2)  # inversion!!!!
        if own != scriptDtx: print 'Anomalous ScriptDtx. Own is:', own
        # broadcast D
        bitcoin.pushtx(signedDtx)
        print 35 * '#', ' MPC initialised ', 35 * '#'
        self.balance += 1000000

        # authorize use of the internet:
        hpUtils.allowFwd(self.ipClient)

        # set up Cashier (observed)
        self.cashier = cashier(self.c)
        self.cashier.addObserver(self)  # obviously not the right way
        self.cashier.start()

        # start control spin
        self.controlSpin()

        # broadcast payment
        print 'Manager broadcasts payment'
        self.pushPayment()

        # terminate cashier
        print "Manager waiting for cashier's termination"
        self.cashier.join()
        #self.c.close()

        print 'Manager terminating'
def create_key(crypto):
    private_key = bitcoin.random_key()
    public_key = bitcoin.privtopub(private_key)
    c.execute(
        'INSERT INTO crypto_key (crypto,public_key,private_key,encrypted_private_key,timestamp) VALUES(?,?,?,?,?)',
        (crypto, public_key, private_key, 0, datetime.datetime.now()))
    conn.commit()
    return public_key
Esempio n. 41
0
def compute_adr_P2SH(args):
    try:
        (priv_num, pubs, nkr, nkt) = args
        pub = bitcoin.privtopub(hexa(priv_num))
        mscript = bitcoin.mk_multisig_script([pub] + pubs[1:], nkr, nkt)
        return bitcoin.p2sh_scriptaddr(mscript)
    except KeyboardInterrupt:
        return "x"
Esempio n. 42
0
def sign(data: bytes,
         private_key_seed_ascii: str,
         hash_function=bitcoin.bin_sha256):
    """Sign data using Ethereum private key.

    :param private_key_seed_ascii: Private key seed as ASCII string
    """

    msghash = hash_function(data)

    priv = utils.sha3(private_key_seed_ascii)
    pub = bitcoin.privtopub(priv)

    # Based on ethereum/tesrt_contracts.py test_ecrecover
    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]])

    # Enforce non-tightly-packed arguments for signing
    # (0x00 left pad)
    # https://github.com/ethereum/web3.py/issues/466
    v = utils.safe_ord(signature[64]) + 27
    r_bytes = signature[0:32]
    r_bytes = pad_left(r_bytes, 32, b"\0")
    r = big_endian_to_int(r_bytes)
    s_bytes = signature[32:64]
    s_bytes = pad_left(s_bytes, 32, b"\0")
    s = big_endian_to_int(s_bytes)

    # Make sure we use bytes data and zero padding stays
    # good across different systems
    r_hex = binascii.hexlify(r_bytes).decode("ascii")
    s_hex = binascii.hexlify(s_bytes).decode("ascii")

    # Convert to Etheruem address format
    addr = utils.big_endian_to_int(
        utils.sha3(bitcoin.encode_pubkey(pub, 'bin')[1:])[12:])

    # Return various bits about signing so it's easier to debug
    return {
        "signature": signature,
        "v": v,
        "r": r,
        "s": s,
        "r_bytes": r_bytes,
        "s_bytes": s_bytes,
        "r_hex": "0x" + r_hex,
        "s_hex": "0x" + s_hex,
        "address_bitcoin": addr,
        "address_ethereum": get_ethereum_address_from_private_key(priv),
        "public_key": pub,
        "hash": msghash,
        "payload":
        binascii.hexlify(bytes([v] + list(r_bytes) + list(s_bytes, )))
    }
Esempio n. 43
0
 def _compute_keys(self):#, field_name, args):
     res={}
     for c in self:#.browse(ids):
         pub_key = bitcoin.privtopub(c.secret_key)
         val={'public_key': 'x', #pub_key,
              'code_fnct': '', #bitcoin.pubtoaddr( pub_key ),
              }
         res[c.id]=val
     return res
Esempio n. 44
0
 def __init__(self, private_key=None, outputs=None, previous_n=0):
     if not private_key:
         self.private_key = bitcoin.electrum_privkey(current_app.config.get('BITCOIN_KEY_SEED'), previous_n+1)
     else:
         self.private_key = private_key
     self.public_key = bitcoin.privtopub(self.private_key)
     self.address = bitcoin.pubtoaddr(self.public_key)
     self.outputs = outputs
     self.created = datetime.datetime.utcnow()
Esempio n. 45
0
def secure_privtopub(priv):
    if len(priv) == 64:
        return encode_hex(secure_privtopub(decode_hex(priv)))
    if openssl:
        k = openssl.CKey()
        k.generate(priv)
        return k.get_pubkey()
    else:
        return bitcoin.privtopub(priv)
Esempio n. 46
0
def pvkey2adr(pvkey, network=5):
    pub_hex = bitcoin.privtopub(pvkey)
    pub_bin = bitcoin.encode_pubkey(pub_hex, "bin_compressed")
    PKH = bitcoin.bin_hash160(pub_bin)
    # script = "\0" + PKH
    # address_bin = bitcoin.bin_hash160(script)
    address = bitcoin.bin_to_b58check(PKH, 0)
    #assert bitcoin.p2sh_scriptaddr(script,network) == address
    return address
def create_encrypted_key(crypto,password):
    private_key = bitcoin.random_key()
    public_key  = bitcoin.privtopub(private_key)    
    # encrypt private key here
    encrypted_private_key=simplecrypt.encrypt(password=password,data=private_key)
    c.execute('INSERT INTO crypto_key (crypto,public_key,private_key,encrypted_private_key,timestamp) VALUES(?,?,?,?,?)',
        (crypto,public_key,0,encrypted_private_key,datetime.datetime.now()))
    conn.commit()
    return public_key
Esempio n. 48
0
def secure_privtopub(priv):
    if len(priv) == 64:
        return encode_hex(secure_privtopub(decode_hex(priv)))
    if openssl:
        k = openssl.CKey()
        k.generate(priv)
        return k.get_pubkey()
    else:
        return bitcoin.privtopub(priv)
Esempio n. 49
0
	def run(self):
		print 'Initialisation of MPC...'

		# exchange public keys
		pubKeyServer = bitcoin.privtopub(self.privS)
		print 'pubKeyServer: ', pubKeyServer
		self.pubKeyClient = txUtils.exchangePubKey(pubKeyServer, self.c)
		print 30*'#', 'Handshake', 30*'#'
		print 'Public Key received from client is: ', self.pubKeyClient

		# receive the signed Dtx and
		signedDtx = self.c.jrecv()
		print 'SignedDtx:' , signedDtx
		#print pprint(bitcoin.deserialize(signedDtx))
		scriptDtx = self.c.jrecv()
		print 'ScriptDtx: ',  scriptDtx
		own = bitcoin.mk_multisig_script([self.pubKeyClient, bitcoin.privtopub(self.privS)], 2,2)  # inversion!!!!
		if own != scriptDtx: print 'Anomalous ScriptDtx. Own is:', own
		# broadcast D
		bitcoin.pushtx(signedDtx)
		print 35*'#',' MPC initialised ', 35*'#'
		self.balance += 1000000

		# authorize use of the internet:
		hpUtils.allowFwd(self.ipClient)

		# set up Cashier (observed)
		self.cashier = cashier(self.c)
		self.cashier.addObserver(self)    # obviously not the right way
		self.cashier.start()

		# start control spin
		self.controlSpin()

		# broadcast payment
		print 'Manager broadcasts payment'
		self.pushPayment()

		# terminate cashier
		print "Manager waiting for cashier's termination"
		self.cashier.join()
		#self.c.close()

		print 'Manager terminating'
Esempio n. 50
0
def showDetails(mnemonic, passphrase="", i=1):

    myMnemonic = mnemonic
    passphrase = passphrase

    mnemo = Mnemonic('english')
    seed = hexlify(mnemo.to_seed(myMnemonic, passphrase=passphrase))
    print 'Seed:\t\t\t\t', seed

    priv = bitcoin.bip32_master_key(unhexlify(seed))
    print 'Xpriv:\t\t\t\t', priv

    key = bitcoin.encode_privkey(bitcoin.bip32_extract_key(priv),
                                 'wif_compressed')
    print 'Key:\t\t\t\t', key

    pub = bitcoin.bip32_privtopub(priv)
    print 'Derived public key:\t', pub
    pubHex = bitcoin.bip32_extract_key(pub)
    print 'public key (hex):\t', pubHex
    print 'Master Key address:\t', bitcoin.pubtoaddr(pubHex)

    print ""
    print "TREZOR Keys:"

    account = 0
    derivedPrivateKey = bitcoin.bip32_ckd(
        bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44 + HARDENED), HARDENED),
        HARDENED + account)
    print 'Derived private key:', derivedPrivateKey

    privateKey = bitcoin.encode_privkey(
        bitcoin.bip32_extract_key(derivedPrivateKey), 'wif_compressed')
    print 'private key (wif):\t', privateKey

    derivedPublicKey = bitcoin.bip32_privtopub(derivedPrivateKey)
    print 'Derived public key:', derivedPublicKey

    publicKeyHex = bitcoin.privtopub(privateKey)
    print 'public key (hex):\t', publicKeyHex

    address = bitcoin.pubtoaddr(publicKeyHex)
    print 'address:\t\t\t', address

    print ""
    print "Account public keys (XPUB)"
    xpubs = []
    for i in range(0, i):
        derivedPrivateKey = bitcoin.bip32_ckd(
            bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44 + HARDENED),
                              HARDENED), HARDENED + i)
        xpub = bitcoin.bip32_privtopub(derivedPrivateKey)
        print 'Account', i, 'xpub:', xpub
        xpubs.append(xpub)

    return xpubs
Esempio n. 51
0
    def auth_counterparty(self, nick, cr):
        #deserialize the commitment revelation
        cr_dict = btc.PoDLE.deserialize_revelation(cr)
        #check the validity of the proof of discrete log equivalence
        tries = jm_single().config.getint("POLICY", "taker_utxo_retries")
        def reject(msg):
            log.info("Counterparty commitment not accepted, reason: " + msg)
            return False
        if not btc.verify_podle(cr_dict['P'], cr_dict['P2'], cr_dict['sig'],
                                cr_dict['e'], self.maker.commit,
                                index_range=range(tries)):
            reason = "verify_podle failed"
            return reject(reason)
        #finally, check that the proffered utxo is real, old enough, large enough,
        #and corresponds to the pubkey
        res = jm_single().bc_interface.query_utxo_set([cr_dict['utxo']],
                                                      includeconf=True)
        if len(res) != 1 or not res[0]:
            reason = "authorizing utxo is not valid"
            return reject(reason)
        age = jm_single().config.getint("POLICY", "taker_utxo_age")
        if res[0]['confirms'] < age:
            reason = "commitment utxo not old enough: " + str(res[0]['confirms'])
            return reject(reason)
        reqd_amt = int(self.cj_amount * jm_single().config.getint(
            "POLICY", "taker_utxo_amtpercent") / 100.0)
        if res[0]['value'] < reqd_amt:
            reason = "commitment utxo too small: " + str(res[0]['value'])
            return reject(reason)
        if res[0]['address'] != btc.pubkey_to_address(cr_dict['P'],
                                                         get_p2pk_vbyte()):
            reason = "Invalid podle pubkey: " + str(cr_dict['P'])
            return reject(reason)

        # authorisation of taker passed

        # Send auth request to taker
        # Need to choose an input utxo pubkey to sign with
        # (no longer using the coinjoin pubkey from 0.2.0)
        # Just choose the first utxo in self.utxos and retrieve key from wallet.
        auth_address = self.utxos[self.utxos.keys()[0]]['address']
        auth_key = self.maker.wallet.get_key_from_addr(auth_address)
        auth_pub = btc.privtopub(auth_key)
        btc_sig = btc.ecdsa_sign(self.kp.hex_pk(), auth_key)
        self.maker.msgchan.send_ioauth(nick, self.utxos.keys(), auth_pub,
                                       self.cj_addr, self.change_addr, btc_sig)
        #In case of *blacklisted (ie already used) commitments, we already
        #broadcasted them on receipt; in case of valid, and now used commitments,
        #we broadcast them here, and not early - to avoid accidentally
        #blacklisting commitments that are broadcast between makers in real time
        #for the same transaction.
        self.maker.transfer_commitment(self.maker.commit)
        #now persist the fact that the commitment is actually used.
        check_utxo_blacklist(self.maker.commit, persist=True)
        return True
def import_key(crypto,private_key):
    c.execute('SELECT * FROM crypto_key WHERE private_key = ?',(private_key,))
    out=c.fetchall()
    if len(out) != 0:
        return None

    public_key=bitcoin.privtopub(private_key)
    c.execute('INSERT INTO crypto_key (crypto,public_key,private_key,encrypted_private_key,timestamp) VALUES(?,?,?,?,?)',
        (crypto,public_key,private_key,0,datetime.datetime.now()))
    conn.commit()
    return public_key   
Esempio n. 53
0
def showDetails(mnemonic, passphrase="", i=1):

    myMnemonic = mnemonic
    passphrase = passphrase


    mnemo = Mnemonic('english')
    seed = hexlify(mnemo.to_seed(myMnemonic, passphrase=passphrase))
    print 'Seed:\t\t\t\t', seed

    priv = bitcoin.bip32_master_key(unhexlify(seed))
    print 'Xpriv:\t\t\t\t', priv

    key = bitcoin.encode_privkey(bitcoin.bip32_extract_key(priv), 'wif_compressed')
    print 'Key:\t\t\t\t', key


    pub = bitcoin.bip32_privtopub(priv)
    print 'Derived public key:\t', pub
    pubHex = bitcoin.bip32_extract_key(pub)
    print 'public key (hex):\t', pubHex
    print 'Master Key address:\t', bitcoin.pubtoaddr(pubHex)


    print ""
    print "TREZOR Keys:"

    account = 0
    derivedPrivateKey = bitcoin.bip32_ckd(bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44+HARDENED), HARDENED), HARDENED+account)
    print 'Derived private key:', derivedPrivateKey

    privateKey = bitcoin.encode_privkey(bitcoin.bip32_extract_key(derivedPrivateKey), 'wif_compressed')
    print 'private key (wif):\t', privateKey


    derivedPublicKey = bitcoin.bip32_privtopub(derivedPrivateKey)
    print 'Derived public key:', derivedPublicKey

    publicKeyHex = bitcoin.privtopub(privateKey)
    print 'public key (hex):\t', publicKeyHex

    address = bitcoin.pubtoaddr(publicKeyHex)
    print 'address:\t\t\t', address

    print ""
    print "Account public keys (XPUB)"
    xpubs = []
    for i in range(0, i):
        derivedPrivateKey = bitcoin.bip32_ckd(bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44+HARDENED), HARDENED), HARDENED+i)
        xpub = bitcoin.bip32_privtopub(derivedPrivateKey)
        print 'Account', i, 'xpub:', xpub
        xpubs.append(xpub)

    return xpubs
Esempio n. 54
0
def eth_privtoaddr(priv) -> str:
    """Generate Ethereum address from a private key.

    God, it was hard to find how this happens.

    https://github.com/ethereum/pyethsaletool/blob/master/pyethsaletool.py#L111

    :return: 0x prefixed hex string
    """
    pub = bitcoin.encode_pubkey(bitcoin.privtopub(priv), 'bin_electrum')
    return "0x" + binascii.hexlify(sha3(pub)[12:]).decode("ascii")
Esempio n. 55
0
	def start_encryption(self, nick, maker_pk):
		if nick not in self.active_orders.keys():
			raise Exception("Counterparty not part of this transaction.")
		self.crypto_boxes[nick] = [maker_pk, enc_wrapper.as_init_encryption(\
		                        self.kp, enc_wrapper.init_pubkey(maker_pk))]
		#send authorisation request
		my_btc_addr = self.input_utxos.itervalues().next()['address']
		my_btc_priv = self.wallet.get_key_from_addr(my_btc_addr)
		my_btc_pub = btc.privtopub(my_btc_priv)
		my_btc_sig = btc.ecdsa_sign(self.kp.hex_pk(), my_btc_priv)
		self.msgchan.send_auth(nick, my_btc_pub, my_btc_sig)
Esempio n. 56
0
    def private_key_to_address(self, pk):
        """
        Convert a private key (in hex format) into an address.
        """
        pub = privtopub(pk)
        pub_byte, priv_byte = get_magic_bytes(self.crypto)

        if priv_byte >= 128:
            priv_byte -= 128 #pybitcointools bug

        return pubtoaddr(pub, pub_byte)
Esempio n. 57
0
def donation_address(reusable_donation_pubkey=None):
    if not reusable_donation_pubkey:
        reusable_donation_pubkey = ('02be838257fbfddabaea03afbb9f16e852'
                                    '9dfe2de921260a5c46036d97b5eacf2a')
    sign_k = binascii.hexlify(os.urandom(32))
    c = btc.sha256(btc.multiply(sign_k,
                                reusable_donation_pubkey, True))
    sender_pubkey = btc.add_pubkeys([reusable_donation_pubkey,
                                     btc.privtopub(c+'01', True)], True)
    sender_address = btc.pubtoaddr(sender_pubkey, get_p2pk_vbyte())
    log.info('sending coins to ' + sender_address)
    return sender_address, sign_k
Esempio n. 58
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)
Esempio n. 59
0
def bip38_decrypt(encrypted_privkey, passphrase, wif=False):
    """
    BIP0038 non-ec-multiply decryption. Returns hex privkey.
    """
    passphrase = normalize('NFC', unicode(passphrase))
    if is_py2:
        passphrase = passphrase.encode('utf8')

    d = unhexlify(changebase(encrypted_privkey, 58, 16, 86))

    d = d[2:]
    flagbyte = d[0:1]
    d = d[1:]
    # respect flagbyte, return correct pair

    if flagbyte == b'\xc0':
        compressed = False
    if flagbyte == b'\xe0':
        compressed = True

    addresshash = d[0:4]
    d = d[4:-4]
    key = scrypt.hash(passphrase,addresshash, 16384, 8, 8)
    derivedhalf1 = key[0:32]
    derivedhalf2 = key[32:64]
    encryptedhalf1 = d[0:16]
    encryptedhalf2 = d[16:32]
    aes = AES.new(derivedhalf2)
    decryptedhalf2 = aes.decrypt(encryptedhalf2)
    decryptedhalf1 = aes.decrypt(encryptedhalf1)
    priv = decryptedhalf1 + decryptedhalf2
    priv = unhexlify('%064x' % (long(hexlify(priv), 16) ^ long(hexlify(derivedhalf1), 16)))
    pub = privtopub(priv)
    if compressed:
        pub = encode_pubkey(pub,'hex_compressed')
    addr = pubtoaddr(pub)

    if is_py2:
        ascii_key = addr
    else:
        ascii_key = bytes(addr,'ascii')

    if sha256(sha256(ascii_key).digest()).digest()[0:4] != addresshash:
        raise Exception('Bip38 password decrypt failed: Wrong password?')
    else:
        formatt = 'wif' if wif else 'hex'
        if compressed:
            return encode_privkey(priv, formatt + '_compressed')
        else:
            return encode_privkey(priv, formatt)