Exemplo n.º 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
Exemplo n.º 2
0
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
Exemplo n.º 3
0
def get_btc_address():
    '''return new btc address and save secret used to generate address'''
    # Generate & Save random address and secret
    secret = base + '_' + str(randint(100000, 9999999999))
    h = hashlib.sha256(secret).digest()
    # key = CBitcoinSecret.from_secret_bytes(h)
    key = CECKey()
    key.set_secretbytes(h)
    address = P2PKHBitcoinAddress.from_pubkey(key.get_pubkey())

    cred = {"Address": address, "Secret": secret}
    # Save generated secret key
    with open("config_keys.txt", "a") as f:
        f.write(str(cred) + '\n')

    return str(address), key, secret
Exemplo n.º 4
0
    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
Exemplo n.º 5
0
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()
digest = sha256(raw_metadata).digest()
Exemplo n.º 6
0
from pycoin.tx.Tx import Tx

my_netcode = "testnet"
#my_netcode = "mainnet"
bitcoin.SelectParams(my_netcode)

my_params = bitcoin.params
my_privkey_prefix = bytes(bytearray([my_params.BASE58_PREFIXES['SECRET_KEY']]))
my_pubaddr_prefix = bytes(bytearray([my_params.BASE58_PREFIXES['PUBKEY_ADDR']]))

# Create the (in)famous correct brainwallet secret key.
h = hashlib.sha256(b'correct horse battery staple').digest()
seckey = CBitcoinSecret.from_secret_bytes(h)

cec_key = CECKey()
cec_key.set_secretbytes(h)

print("Secret key  hex: ", seckey.hex());
btc_addr = encoding.public_pair_to_bitcoin_address(cec_key.get_pubkey(), address_prefix=my_pubaddr_prefix)
print("Bitcoin address: ", btc_addr)

# Create a redeemScript, with public key and checksig op code (0xac)
# Similar to a scriptPubKey the redeemScript must be satisfied for the funds to be spent.
txin_redeemScript = CScript([seckey.pub, OP_CHECKSIG])
print("Public key of address #", seckey.pub.hex())
# 0x21 + secret.pub + OP_CHECKSIG (0x87)
print("Tx-in Redeem Script: ", b2x(txin_redeemScript))

# Create the magic P2SH scriptPubKey format from that redeemScript. You should
# look at the CScript.to_p2sh_scriptPubKey() function in bitcoin.core.script to
# understand what's happening, as well as read BIP16:
## Version of public addr, script addr, secret key
## mainnet - 0, 5, 128
## testnet and regtest - 111, 196, 239

print()
print("CECKey example - ", my_netcode)
print("Pubkey Addr Ver: ", bitcoin.params.BASE58_PREFIXES['PUBKEY_ADDR'],
      ", Secret Key Ver: ", bitcoin.params.BASE58_PREFIXES['SECRET_KEY'])

# use CECKey class
cec_key = CECKey()
#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())