def blockstack_name_renew(name,
                          privatekey,
                          register_addr=None,
                          subsidy_key=None,
                          user_public_key=None,
                          safety_checks=False):

    test_proxy = make_proxy()
    blockstack_client.set_default_proxy(test_proxy)

    name_cost_info = test_proxy.get_name_cost(name)
    if register_addr is None:
        register_addr = pybitcoin.BitcoinPrivateKey(
            privatekey).public_key().address()
    else:
        assert register_addr == pybitcoin.BitcoinPrivateKey(
            privatekey).public_key().address()

    resp = blockstack_client.do_renewal(name,
                                        privatekey,
                                        privatekey,
                                        name_cost_info['satoshis'],
                                        test_proxy,
                                        test_proxy,
                                        config_path=test_proxy.config_path,
                                        proxy=test_proxy,
                                        safety_checks=safety_checks)

    api_call_history.append(APICallRecord("renew", name, resp))
    return resp
def namespace_preorder(namespace_id, privatekey, reveal_addr=None, proxy=None):
    """
    namespace preorder
    Generate a register change address private key, if not given
    """

    if proxy is None:
        proxy = get_default_proxy()

    reveal_privkey_wif = None

    if reveal_addr is None:
        privkey = pybitcoin.BitcoinPrivateKey()
        pubkey = privkey.public_key()
        reveal_addr = pubkey.address()

        reveal_privkey_wif = privkey.to_wif()
        print reveal_privkey_wif
        print reveal_addr

    # make sure the reveal address is *not* the address of this private key
    privkey = pybitcoin.BitcoinPrivateKey(privatekey)
    if reveal_addr == privkey.public_key().address():
        return {"error": "Reveal address derived from private key"}

    result = proxy.namespace_preorder(namespace_id, reveal_addr, privatekey)

    if 'error' in result:
        return result

    if reveal_privkey_wif is not None:
        result['reveal_privatekey'] = reveal_privkey_wif

    return result
def preorder(name, privatekey, register_addr=None, proxy=None, tx_only=False):
    """
    preorder.
    Generate a private key to derive a change address for the register,
    if one is not given already.
    """

    register_privkey_wif = None

    if register_addr is None:
        privkey = pybitcoin.BitcoinPrivateKey()
        pubkey = privkey.public_key()

        register_addr = pubkey.address()

        register_privkey_wif = privkey.to_wif()
        print register_privkey_wif
        print register_addr

    # make sure the reveal address is *not* the address of this private key
    privkey = pybitcoin.BitcoinPrivateKey(privatekey)
    if register_addr == privkey.public_key().address():
        return {"error": "Register address derived from private key"}

    resp = {}

    if proxy is None:
        proxy = get_default_proxy()

    try:
        if tx_only:

            # get unsigned preorder
            resp = proxy.preorder_tx(name, privatekey, register_addr)

        else:
            # send preorder
            resp = proxy.preorder(name, privatekey, register_addr)

    except Exception as e:
        resp['error'] = str(e)

    if 'error' in resp:
        return resp

    # give the client back the key to the addr we used
    if register_privkey_wif is not None:
        resp['register_privatekey'] = register_privkey_wif

    return resp
Esempio n. 4
0
    def __init__(self, pk_wif, value_str):
        pk = pybitcoin.BitcoinPrivateKey(pk_wif)

        self._pk = pk
        self.privkey = pk_wif
        self.pubkey_hex = pk.public_key().to_hex()
        self.addr = pk.public_key().address()
        self.value = int(value_str)
    def __init__(self, pk_wif, value_str):
        pk = pybitcoin.BitcoinPrivateKey(pk_wif)

        self._pk = pk
        self.privkey = pk_wif
        self.pubkey_hex = pk.public_key().to_hex(
        )  # coordinate (uncompressed) EC public key
        self.ec_pubkey_hex = keylib.ECPrivateKey(pk_wif).public_key().to_hex(
        )  # parameterized (compressed) EC public key
        self.addr = pk.public_key().address()
        self.value = int(value_str)
Esempio n. 6
0
    def get_wallet(self, rpc_token=None):
        """ Keeps payment privkey in memory (instead of disk)
            for the time that server is alive
        """

        data = {}
        valid_rpc_token = get_rpc_token()

        if str(valid_rpc_token) != str(rpc_token):
            data['error'] = "Incorrect RPC token"
            return json.dumps(data)

        data['payment_address'] = self.payment_address
        data['owner_address'] = self.owner_address
        data['data_pubkey'] = pybitcoin.BitcoinPrivateKey( self.get_data_privkey() ).public_key().to_hex()

        data['payment_privkey'] = self.get_payment_privkey()
        data['owner_privkey'] = self.get_owner_privkey()
        data['data_privkey'] = self.get_data_privkey()

        return json.dumps(data)
Esempio n. 7
0
    """
   Unit tests.
   """

    import pybitcoin
    import json

    # hack around absolute paths
    current_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                               ".."))
    sys.path.insert(0, current_dir)

    from storage import serialize_mutable_data, parse_mutable_data
    from user import make_mutable_data_info

    pk = pybitcoin.BitcoinPrivateKey()
    data_privkey = pk.to_hex()
    data_pubkey = pk.public_key().to_hex()

    test_data = [
        ["my_first_datum", "hello world", 1, "unused", None],
        ["/my/second/datum", "hello world 2", 2, "unused", None],
        [
            "user_profile", '{"name":{"formatted":"judecn"},"v":"2"}', 3,
            "unused", None
        ],
        ["empty_string", "", 4, "unused", None],
    ]

    def hash_data(d):
        return pybitcoin.hash.hex_hash160(d)
Esempio n. 8
0
    def __init__(self,
                 tx_path=None,
                 tx_list=None,
                 tx_grouping=1,
                 start_block=0,
                 start_time=0x11111111,
                 difficulty=1.0,
                 initial_utxos={},
                 **kw):
        """
        Create a mock bitcoind connection, either from a 
        list of serialized transactions on-file, or a given Python
        list of serialized transactions.

        Transactions will be bundled into blocks in groups of size tx_grouping.
        """

        self.block_hashes = {}  # map block ID to block hash
        self.blocks = {
        }  # map block hash to block info (including transaction IDs)
        self.txs = {}  # map tx hash to a list of transactions
        self.next_block_txs = []  # next block's transactions

        self.difficulty = difficulty
        self.time = start_time
        self.start_block = start_block
        self.end_block = start_block

        self.block_hashes[start_block - 1] = '00' * 32
        self.blocks['00' * 32] = {}

        tx_recs = []
        if tx_path is not None:
            with open(tx_path, "r") as f:
                tmp = f.readlines()
                tx_recs = [l.strip() for l in tmp]

        elif tx_list is not None:
            tx_recs = tx_list

        # prepend utxos
        if len(initial_utxos) > 0:
            initial_outputs = []
            for (privkey, value) in initial_utxos.items():

                addr = pybitcoin.BitcoinPrivateKey(
                    privkey).public_key().address()
                out = {
                    'value': value,
                    'script_hex': pybitcoin.make_pay_to_address_script(addr)
                }
                initial_outputs.append(out)

            tx = {
                'inputs': [],
                'outputs': initial_outputs,
                'locktime': 0,
                'version': 0xff
            }

            tx_hex = tx_serialize(tx['inputs'], tx['outputs'], tx['locktime'],
                                  tx['version'])
            tx_recs = [tx_hex] + tx_recs

        i = 0
        while True:

            txs = []
            count = 0
            while i < len(tx_recs) and count < tx_grouping:
                txs.append(tx_recs[i])
                i += 1

            if len(txs) > 0:
                for tx in txs:
                    self.sendrawtransaction(tx)
                self.flush_transactions()

            if i >= len(tx_recs):
                break
Esempio n. 9
0
    keyring = []
    unfunded = []
    keyring_path = "%s.keyring" % namespace_id

    if os.path.exists(keyring_path):
        print "import from '%s'" % keyring_path
        try:
            tmp = []
            with open(keyring_path, "r") as f:
                tmp = f.readlines()

            keyring = []
            tmp2 = [k.strip() for k in tmp]

            for pk in tmp2:
                addr = pybitcoin.BitcoinPrivateKey(pk).public_key().address()
                balance = get_balance(chaincom_id, chaincom_secret, addr)
                print "%s (%s) balance: %s" % (pk, addr, balance)

                total_balance += balance
                if balance > 54000:
                    keyring.append(pk)
                else:
                    unfunded.append(addr)

        except Exception, e:
            log.exception(e)
            pass

    if len(keyring) == 0:
        pk = pybitcoin.BitcoinPrivateKey(privkey_str)
Esempio n. 10
0
    chaincom_client = pybitcoin.ChainComClient(chaincom_id, chaincom_secret)

    # get our namespace's names
    try:
        with open(sys.argv[1], "r") as f:
           names_json = f.read()

    except Exception, e:
        traceback.print_exc()
        print >> sys.stderr, "Failed to read '%s'" % sys.argv[1]
        sys.exit(1)

    privkey_str = sys.argv[3]
    namespace_id = sys.argv[2]

    privkey = pybitcoin.BitcoinPrivateKey(privkey_str)
    importer_address = privkey.public_key().address()

    try:
        names = json.loads(names_json)
    except Exception, e:
        traceback.print_exc()
        print >> sys.stderr, "Invalid JSON file '%s'" % sys.argv[1]
        sys.exit(1)

    # record name status
    logfile_path = namespace_id + ".sent"
    failed_path = namespace_id + ".failed"
    confirmed_path = namespace_id + ".confirmed"

    sent_names_json = []
    def __init__(self, save_file=None, tx_path=None, tx_list=None, tx_grouping=1, \
                 start_block=0, start_time=0x11111111, difficulty=1.0, initial_utxos={}, \
                 spv_headers_path=None, **kw ):
        """
        Create a mock bitcoind connection, either from a 
        list of serialized transactions on-file, or a given Python
        list of serialized transactions.

        If possible, restore from a saved file.  This trumps all other options.

        Transactions will be bundled into blocks in groups of size tx_grouping.
        """

        assert save_file is not None

        self.block_hashes = {}      # map block ID to block hash 
        self.blocks = {}            # map block hash to block info (including transaction IDs)
        self.txs = {}               # map tx hash to a list of transactions
        self.txid_to_blockhash = {} # map tx hash to block hash
        self.next_block_txs_path = None     # next block's transactions
        self.difficulty = difficulty 
        self.time = start_time 
        self.start_block = start_block
        self.end_block = start_block
        self.spv_headers_path = spv_headers_path

        # for compatibility with blockstack_client (should refer to nothing)
        self.opts = {
            'bitcoind_server': "localhost",
            'bitcoind_port': 31113
        }
        
        self.block_hashes[ start_block - 1 ] = '00' * 32
        self.blocks[ '00' * 32 ] = {}

        self.save_file = save_file
        if save_file is not None:
            self.next_block_txs_path = save_file + ".next"

        if save_file is not None and os.path.exists( save_file ):
            self.restore( save_file )
        
        else:
            # the initial utxos might be a serialized CSV (i.e. loaded directly from the config file).
            # if so, then parse it 
            if type(initial_utxos) in [str, unicode]:
                tmp = {}
                parts = initial_utxos.split(",")
                for utxo in parts:
                    privkey, value = utxo.split(':')
                    tmp[ privkey ] = int(value)

                initial_utxos = tmp
                
            tx_recs = []
            if tx_path is not None:
                with open( tx_path, "r" ) as f:
                    tmp = f.readlines()
                    tx_recs = [l.strip() for l in tmp]

            elif tx_list is not None:
                tx_recs = tx_list 

            # prepend utxos
            if len(initial_utxos) > 0:
                initial_outputs = []
                for (privkey, value) in initial_utxos.items():
                    
                    addr = pybitcoin.BitcoinPrivateKey( privkey ).public_key().address()
                    out = {
                        'value': value,
                        'script_hex': pybitcoin.make_pay_to_address_script( addr )
                    }
                    initial_outputs.append( out )

                tx = {
                    'inputs': [],
                    'outputs': initial_outputs,
                    'locktime': 0,
                    'version': 0xff
                }
                
                tx_hex = tx_serialize( tx['inputs'], tx['outputs'], tx['locktime'], tx['version'] )
                tx_recs = [tx_hex] + tx_recs
          
            # feed all txs
            i = 0 
            while True:
                
                txs = []
                count = 0
                while i < len(tx_recs) and count < tx_grouping:
                    txs.append( tx_recs[i] )
                    i += 1

                if len(txs) > 0:
                    for tx in txs:
                        self.sendrawtransaction( tx )
                    self.flush_transactions()
                
                if i >= len(tx_recs):
                    break
Esempio n. 12
0
def address(sk):
    return pybitcoin.BitcoinPrivateKey(sk).public_key().address()