コード例 #1
0
def deriveAddress(privateKey, compressed, blockChain):
    """
    Turn a private key into an address.
    privateKey must be in binary format.
    """
    privKey = CECKey()
    privKey.set_secretbytes(privateKey)
    privKey.set_compressed(compressed)
    publicKey = privKey.get_pubkey()
    hash1 = hashlib.sha256(publicKey).digest()

    ripemd160 = hashlib.new('ripemd160')
    ripemd160.update(hash1)
    ripe = ripemd160.digest()

    if blockChain == 'bitcoin':
        ripeWithNetworkPrefix = b'\x00' + ripe
    elif blockChain.startswith('testnet'):
        ripeWithNetworkPrefix = b'\x6F' + ripe
    else:
        raise Exception("'blockChain' parameter is not set correctly")

    checksum = hashlib.sha256(
        hashlib.sha256(ripeWithNetworkPrefix).digest()).digest()[:4]
    binaryBitcoinAddress = ripeWithNetworkPrefix + checksum
    numberOfZeroBytesOnBinaryBitcoinAddress = 0
    while binaryBitcoinAddress[0:1] == b'\x00':  # while the first byte is null
        numberOfZeroBytesOnBinaryBitcoinAddress += 1
        binaryBitcoinAddress = binaryBitcoinAddress[
            1:]  # take off the first byte
    base58encoded = encode(binaryBitcoinAddress)  # encode into base58
    return "1" * numberOfZeroBytesOnBinaryBitcoinAddress + base58encoded
コード例 #2
0
ファイル: script.py プロジェクト: proger/utxo-dump
def pk_scriptdecompress(pk):
    # https://github.com/bitcoin/bitcoin/blob/5961b23898ee7c0af2626c46d5d70e80136578d3/src/compressor.cpp#L118
    xpk = bytes(bytearray([pk[0] - 2]) + pk[1:])

    pk = CPubKey(xpk)
    cec = CECKey()
    cec.set_compressed(True)
    res = cec.set_pubkey(pk)
    if res is None:
        raise Exception(ssl_get_error())
    cec.set_compressed(False)
    pubkey = cec.get_pubkey()
    return CPubKey(pubkey, _cec_key=cec)
コード例 #3
0
ファイル: utilities.py プロジェクト: quebin31/keyserver-rs
def generate_random_keypair():
    """Generate a random bitcoin address, a ECDSA keypair."""

    # Generate keys
    secret = os.urandom(16)
    keypair = CECKey()
    keypair.set_compressed(True)
    keypair.set_secretbytes(secret)
    public_key = keypair.get_pubkey()

    # Generate key addr
    key_addr = str(P2PKHBitcoinAddress.from_pubkey(public_key))
    return key_addr, keypair
コード例 #4
0
ファイル: lib.py プロジェクト: wizardofozzie/chain-python
    def sign(self, template, privateKeys):

        # convert all of the privateKeys to a standard binary format for us to work with
        privateKeysBinary = convertPrivateKeysToBinaryFormat(
            privateKeys, self.blockChain)
        """
        keyCollection is a dictionary where the key of the dict is an address and the value is a 
        tuple with (privKey, compressed)
            where `privKey` is the private key in binary format
            and `compressed` is a bool indicating whether or not the corresponding public key is compressed.
        """
        keyCollection = generateKeyCollection(privateKeysBinary,
                                              self.blockChain)

        if not 'inputs' in template:
            raise Exception(
                "This template has no inputs. There is nothing to sign.")

        for inputIndex in range(len(
                template['inputs'])):  # For each input in the template...
            for signatureIndex in range(
                    len(template['inputs'][inputIndex]
                        ['signatures'])):  # For each signature in the input...
                address = template['inputs'][inputIndex]['signatures'][
                    signatureIndex][
                        'address']  # Get the address out of the template to make this code easier to read
                if address in keyCollection:  # if we have the private key needed for this signature..
                    privateKeyBinary, compressed = keyCollection[address]
                    privKey = CECKey(
                    )  # This CECKey object type is from the python-bitcoinlib library
                    privKey.set_secretbytes(privateKeyBinary)
                    privKey.set_compressed(compressed)
                    hash_to_sign = template['inputs'][inputIndex][
                        'signatures'][signatureIndex]['hash_to_sign']
                    signature = privKey.sign(unhexlify(hash_to_sign))

                    # We now have the signature. Let's put the signature and the pubkey into the template.
                    template['inputs'][inputIndex]['signatures'][
                        signatureIndex]['signature'] = hexlify(
                            signature).decode('ascii')
                    template['inputs'][inputIndex]['signatures'][
                        signatureIndex]['public_key'] = hexlify(
                            privKey.get_pubkey()).decode('ascii')
        return template
コード例 #5
0
# cargo run

BASE_URL_A = "http://0.0.0.0:8082"
BASE_URL_B = "http://0.0.0.0:8081"
bitcoin.SelectParams("regtest")

# Init Bitcoin RPC
rpc_user = "******"
rpc_password = "******"
rpc_connection = AuthServiceProxy("http://%s:%[email protected]:18443" %
                                  (rpc_user, rpc_password))

# Generate keys
secret = os.urandom(16)
keypair = CECKey()
keypair.set_compressed(True)
keypair.set_secretbytes(secret)
private_key = keypair.get_privkey()
public_key = keypair.get_pubkey()

# Generate key addr
key_addr = str(P2PKHBitcoinAddress.from_pubkey(public_key))

# Construct Payload
header = Header(name="Something wicked", value="this way comes")
entry = Entry(headers=[header], entry_data=b'This gonna be so f*****g fast')
timestamp = int(time())
metadata = AddressMetadata(timestamp=timestamp, ttl=3000, entries=[entry])

# Sign
raw_metadata = metadata.SerializeToString()
コード例 #6
0
#cec_key.set_secretbytes(privkey_bytes)
random_nbr = 1  #util.randrange(ecdsa.generator_secp256k1.order())
my_secret_exp = b2h(encoding.to_bytes_32(random_nbr))
cec_key.set_secretbytes(bitcoin.core.x(my_secret_exp))

print("Private Key dec: ", random_nbr)
print("Private Key hex: ", my_secret_exp)
privkey_wif = encoding.secret_exponent_to_wif(eval('0x' + my_secret_exp),
                                              wif_prefix=my_privkey_prefix)
print("Private key WIF: ", privkey_wif)
privkey_wif = encoding.secret_exponent_to_wif(eval('0x' + my_secret_exp),
                                              False,
                                              wif_prefix=my_privkey_prefix)
print("   uncompressed: ", privkey_wif)

cec_key.set_compressed(True)

print()
pubkey_pair = encoding.sec_to_public_pair(cec_key.get_pubkey())
print("Public key pair: ", pubkey_pair)

(pub_key_x, pub_key_y) = pubkey_pair
compressed_indicator = True if (pub_key_y % 2) == 0 else False
print("Public key y parity? ", 'even' if compressed_indicator else 'odd')

#print("Private key hexlify: ", hexlify(cec_key.get_privkey()))
print("Public  key    hex: ", bitcoin.core.b2x(cec_key.get_pubkey()))
cec_key.set_compressed(False)
print("      uncompressed: ", bitcoin.core.b2x(cec_key.get_pubkey()))

addr_compressed = encoding.public_pair_to_bitcoin_address(