示例#1
0
    def fund_address(self, address: Address, value: float):
        """
        Sends money to an address using a UTXO of the mining address
        :param address: the address that will receive the coins
        :param value: the value that the address will receive
        :return: the transaction id and
        """
        key = CBitcoinSecret(COINBASE_KEY)
        coinbase_addr = Address(key)

        unspents = self.proxy.listunspent(minconf=100,
                                          addrs=[coinbase_addr.address])
        unspents.sort(key=lambda x: x['confirmations'], reverse=True)
        oldest_utxo = next(
            x for x in unspents
            if Coin.from_satoshi(x['amount']).bitcoin() >= value + self.fee)

        coinbase_addr.txid = oldest_utxo['outpoint'].hash
        coinbase_addr.vout = oldest_utxo['outpoint'].n

        coinbase_addr.value = Coin.from_satoshi(
            oldest_utxo['amount']).bitcoin()
        address.value = value

        # change address is always the second output
        txid = self.create_transaction(
            [coinbase_addr], [address, coinbase_addr],
            values=[value, coinbase_addr.value - self.fee - value])

        self.log.debug("Address: {}".format(address.address))
        self.log.debug("Tx: {}".format(txid))

        return txid, address.vout
示例#2
0
def print_verbose(signature, key, msg):
    secret = CBitcoinSecret(key)
    address = P2PKHBitcoinAddress.from_pubkey(secret.pub)
    message = BitcoinMessage(msg)
    print('Address: %s' % address)
    print('Message: %s' % msg)
    print('Signature: %s' % signature)
    print('Verified: %s' % VerifyMessage(address, message, signature))
    print('\nTo verify using bitcoin core:')
    print('\n`bitcoin-cli verifymessage %s \'%s\' \'%s\'`\n' % (address, signature.decode('ascii'), msg))
    def test_sign_message_simple(self):
        key = CBitcoinSecret(
            "L4vB5fomsK8L95wQ7GFzvErYGht49JsCPJyJMHpB4xGM6xgi2jvG")
        address = "1F26pNMrywyZJdr22jErtKcjF8R3Ttt55G"
        message = address

        message = BitcoinMessage(message)
        signature = SignMessage(key, message)

        self.assertTrue(signature)
        self.assertTrue(VerifyMessage(address, message, signature))
    def test_sign_message_vectors(self):
        for vector in load_test_vectors('signmessage.json'):
            key = CBitcoinSecret(vector['wif'])
            message = BitcoinMessage(vector['address'])

            signature = SignMessage(key, message)

            self.assertTrue(signature,
                            "Failed to sign for [%s]" % vector['address'])
            self.assertTrue(
                VerifyMessage(vector['address'], message, vector['signature']),
                "Failed to verify signature for [%s]" % vector['address'])
示例#5
0
def generate_vault():
    bitcointx.SelectParams('mainnet')
    m = int(input('How many total signatures will be required (aka "m"): '))
    n = int(input('How many total keys do you want to generate (aka "n"): '))
    privkeys = []
    pubkeys = []
    for counter in range(1, n):
        privkey = CBitcoinSecret.from_secret_bytes(os.urandom(32))
        pubkey = privkey.pub
        privkeys.append(privkey)
        pubkeys.append(pubkey)
        counter = counter + 1
    redeem_list = generate_multisig_redeem_list(pubkeys, m)
    script_pub_key = CScript([OP_0, sha256(CScript(redeem_list)).digest()])
    address = P2WSHBitcoinAddress.from_scriptPubKey(script_pub_key)
    PATH = '/mnt/keys'
    if not os.path.isdir(PATH):
        subprocess.run(['mkdir', PATH])
    counter = 1
    while counter <= len(privkeys):
        if counter == 1:
            input('Insert a USB Drive. Press any key when complete.')
        else:
            input('Insert another USB Drive. Press any key when complete or \
press CTL+C to cancel.')
        subprocess.run(['lsblk'])
        dev = input(
            'Enter the device and partition of the USB drive (ex: sdb1): ')
        subprocess.run(['umount', f'/dev/{dev}'],
                       stdout=subprocess.DEVNULL,
                       stderr=subprocess.DEVNULL)
        subprocess.run(['mount', f'/dev/{dev}', PATH])
        try:
            if not dev:
                raise ValueError('Bad Path.')
            keypath = os.path.join(PATH, f'key{counter}')
            addresspath = os.path.join(PATH, 'address')
            scriptpath = os.path.join(PATH, 'script')
            with open(keypath, 'w') as key_file:
                key_file.write(str(privkeys[(counter - 1)]))
            with open(addresspath, 'w') as address_file:
                address_file.write(str(address))
            with open(scriptpath, 'w') as script_file:
                script_file.write(str(redeem_list))
            for file in [keypath, addresspath, scriptpath]:
                os.chmod(file, S_IREAD | S_IRGRP | S_IROTH)
        except Exception as e:
            print(e)
            print('Bad path given. Try again.')
            continue
        subprocess.run(['umount', f'/dev/{dev}'])
        counter = counter + 1
    print('Process complete.')
    def _sign(cls, account: Account, hashbuf, hash_type) -> bytes:
        sec_key = CBitcoinSecret.from_bytes(
            bytes.fromhex(remove_0x_prefix(account.private_key)))
        sig_script_bytes: bytes = sec_key.sign(hashbuf)
        sig_script_bytes += bytes([hash_type & 0xff])
        public_key = Web3.toBytes(hexstr=account.public_key.decode())

        script_buffer = BytesIO()
        script_buffer.write(bytes([len(sig_script_bytes)]))
        script_buffer.write(sig_script_bytes)
        script_buffer.write(bytes([len(public_key)]))
        script_buffer.write(public_key)
        return script_buffer.getvalue()
示例#7
0
def sign_transaction(tx, privkeys):
    witness_list = list(tx.witness.vtxinwit[0].scriptWitness.stack)
    sighash = SignatureHash(tx.witness, tx, 0, SIGHASH_ALL)
    signatures = []
    for privkey in privkeys:
        privkey = CBitcoinSecret.from_bytes(privkey)
    for privkey in privkeys:
        signatures.append(privkey.sign(sighash) + bytes([SIGHASH_ALL]))
    counter = 0
    for signature in signatures:
        witness_list.insert(counter, signature)
        counter = counter + 1
    witness_script = CScriptWitness(tuple(witness_list))
    tx.witness = CTxWitness(tuple([CTxInWitness(witness_script)]))
    return tx.serialize()
示例#8
0
def sign_message(key, msg):
    secret = CBitcoinSecret(key)
    message = BitcoinMessage(msg)
    return SignMessage(secret, message)
示例#9
0
    sys.stderr.write('Sorry, Python 3.x required by this example.\n')
    sys.exit(1)

import hashlib

from bitcointx import SelectParams
from bitcointx.core import b2x, lx, COIN, COutPoint, CMutableTxOut, CMutableTxIn, CMutableTransaction, Hash160
from bitcointx.core.script import CScript, OP_DUP, OP_HASH160, OP_EQUALVERIFY, OP_CHECKSIG, SignatureHash, SIGHASH_ALL
from bitcointx.core.scripteval import VerifyScript, SCRIPT_VERIFY_P2SH
from bitcointx.wallet import CBitcoinAddress, CBitcoinSecret

SelectParams('mainnet')

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

# Same as the txid:vout the createrawtransaction RPC call requires
#
# lx() takes *little-endian* hex and converts it to bytes; in Bitcoin
# transaction hashes are shown little-endian rather than the usual big-endian.
# There's also a corresponding x() convenience function that takes big-endian
# hex and converts it to bytes.
txid = lx('7e195aa3de827814f172c362fcf838d92ba10e3f9fdd9c3ecaf79522b311b22d')
vout = 0

# Create the txin structure, which includes the outpoint. The scriptSig
# defaults to being empty.
txin = CMutableTxIn(COutPoint(txid, vout))

# We also need the scriptPubKey of the output we're spending because
示例#10
0
 def compute_key(key_index: int) -> CBitcoinSecret:
     """
     Deterministically generate a key from an index.
     """
     h = hashlib.sha256(bytes(key_index)).digest()
     return CBitcoinSecret.from_secret_bytes(h)
示例#11
0
import hashlib
from config import *
from bitcointx.core import b2x
from bitcointx.core.script import *
from bitcointx.wallet import CCoinAddress, CBitcoinSecret
import binascii

unhexlify = binascii.unhexlify

# # Create AW, RW and secret and public keys
AW_privkeys = [
    CBitcoinSecret.from_secret_bytes(
        hashlib.sha256(b'Active Wallet Brain Secret 1').digest()),
    CBitcoinSecret.from_secret_bytes(
        hashlib.sha256(b'Active Wallet Brain Secret 2').digest()),
    CBitcoinSecret.from_secret_bytes(
        hashlib.sha256(b'Active Wallet Brain Secret 3').digest())
]
RW_privkeys = [
    CBitcoinSecret.from_secret_bytes(
        hashlib.sha256(b'Recovery Wallet Brain Secret 1').digest()),
    CBitcoinSecret.from_secret_bytes(
        hashlib.sha256(b'Recovery Wallet Brain Secret 2').digest()),
    CBitcoinSecret.from_secret_bytes(
        hashlib.sha256(b'Recovery Wallet Brain Secret 3').digest())
]

AW_pubkeys = [x.pub for x in AW_privkeys]

RW_pubkeys = [x.pub for x in RW_privkeys]
示例#12
0
    def dumpprivkey(self, addr):
        """Return the private key matching an address
        """
        r = self._call('dumpprivkey', str(addr))

        return CBitcoinSecret(r)