Send bitcoins to address

        :param wallet_id: bitgo wallet id
        :param address: bitcoin address
        :param amount: btc amount in satoshis
        :param split: create new outputs if needed
        :return: boolean
515581
def send(self, wallet_id, passcode, address, amount, message='', fee=None, fan_unspend=10):
        
        MINIMAL_FEE = 20000
        MINIMAL_SPLIT = 10000000

        wallet = self.get_wallet(wallet_id)

        if not wallet['spendingAccount']:
            raise NotSpendableWallet()

        if not wallet['isActive']:
            raise NotActiveWallet()

        if amount < 10000:
            raise Exception('amount to small')

        if wallet['confirmedBalance'] < amount:
            raise NotEnoughFunds('Not enough funds: balance %s amount %s' %
                                 (wallet['confirmedBalance'], amount)
            )

        change_address = self.create_address(wallet_id, chain=1)
        usableKeychain = False
        spendables = []
        chain_paths = []
        p2sh = []
        payables = [(address, amount)]
        keychain_path = ""

        for keychain in wallet['private']['keychains']:
            keychain_path = keychain['path'][1:]
            keychain = self.get_keychain(keychain['xpub'])
            if 'encryptedXprv' not in keychain:
                continue
            usableKeychain = True
            break

        if not usableKeychain:
            raise BitGoError("didn't found a spendable keychain")

        data = json.loads(keychain['encryptedXprv'])
        #add base64 paddings
        for k in ['iv', 'salt', 'ct']:
            data[k] = data[k] + "=="
        cipher = sjcl.SJCL()
        xprv = cipher.decrypt(data, passcode)

        unspents = self.get_unspents(wallet_id)
        unspents = filter(lambda u: u['confirmations'] > 0, unspents['unspents'][::-1])

        total_value = 0
        for d in unspents:
            path = keychain_path + d['chainPath']
            chain_paths.append(path)
            p2sh.append(h2b(d["redeemScript"]))
            spendables.append(Spendable(d["value"],
                                  h2b(d["script"]),
                                  h2b_rev(d["tx_hash"]),
                                  d["tx_output_n"]))

            total_value += d['value']
            if total_value > amount:
                break

        # make many outputs?
        if len(unspents) < 5 and (total_value > (amount + MINIMAL_SPLIT)) and fan_unspend > 0:
            fee = self.calculate_fee(len(spendables), fan_unspend)
            value = (total_value - amount - fee) / fan_unspend
            for i in range(fan_unspend):
                payables.append((change_address, value))
        elif total_value > (amount + MINIMAL_FEE):
            # add a change address
            if fee is None:
                fee = self.calculate_fee(len(spendables), 2)
            value = total_value - amount - fee
            if value > 10000: #avoid dust
                payables.append((change_address, value))

        p2sh_lookup = build_p2sh_lookup(p2sh)

        spendable_keys = []

        priv_key = BIP32Node.from_hwif(xprv)

        spendable_keys = [priv_key.subkey_for_path(path) for path in chain_paths]

        hash160_lookup = build_hash160_lookup([key.secret_exponent() for key in spendable_keys])

        tx = create_tx(spendables, payables)

        tx.sign(hash160_lookup=hash160_lookup, p2sh_lookup=p2sh_lookup)

        r = requests.post(self.url + '/tx/send', {
                'tx': tx.as_hex(),
                'message': message
            }, headers={
                'Authorization': 'Bearer %s' % self.access_token,
            })

        return r.json()
633570
def btc_make_payment_script( address, segwit=None, **ignored ):
    
    
    if segwit is None:
        segwit = get_features('segwit')

    # is address bech32-encoded?
    witver, withash = segwit_addr_decode(address)
    if witver is not None and withash is not None:
        # bech32 segwit address
        if not segwit:
            raise ValueError("Segwit is disabled")

        if len(withash) == 20:
            # p2wpkh
            script_hex = '0014' + withash.encode('hex')
            return script_hex
            
        elif len(withash) == 32:
            # p2wsh
            script_hex = '0020' + withash.encode('hex')
            return script_hex

        else:
            raise ValueError("Unrecognized address '%s'" % address )

    else:
        # address is b58check-encoded
        vb = keylib.b58check.b58check_version_byte(address)
        if vb == version_byte:
            # p2pkh
            hash160 = binascii.hexlify( keylib.b58check.b58check_decode(address) )
            script = 'OP_DUP OP_HASH160 {} OP_EQUALVERIFY OP_CHECKSIG'.format(hash160)
            script_hex = btc_script_to_hex(script)
            return script_hex

        elif vb == multisig_version_byte:
            # p2sh
            hash160 = binascii.hexlify( keylib.b58check.b58check_decode(address) )
            script = 'OP_HASH160 {} OP_EQUAL'.format(hash160)
            script_hex = btc_script_to_hex(script)
            return script_hex

        else:
            raise ValueError("Unrecognized address '%s'" % address )
814584
def sendtoaddress(self, recv_addr, amount, comment=""):
        """"""
        return self.req("sendtoaddress", [recv_addr, amount, comment])
697127
def get_address(self, address):
        
        
        params = self.build_basic_request()
        params['address'] = address

        response = util.call_api("merchant/{0}/address_balance".format(self.identifier), params,
                                 base_url=self.service_url)
        json_response = json.loads(response)
        self.parse_error(json_response)
        return Address(json_response['balance'],
                       json_response['address'],
                       None,
                       json_response['total_received'])
1296482
def address_to_oa_address(btc_address)
      begin
        btc_hex = decode_base58(btc_address)
        btc_hex = '0' +btc_hex if btc_hex.size==47
        address = btc_hex[0..-9] # bitcoin address without checksum
        named_addr = OA_NAMESPACE.to_s(16) + address
        oa_checksum = checksum(named_addr)
        encode_base58(named_addr + oa_checksum)
      rescue ArgumentError
        nil # bech32 format fails to decode. TODO define OA address for segwit
      end
    end
382710
function Bitid(params) {
  params = params || {};
  var self = this;

  this._nonce = params.nonce;
  this.callback = url.parse(params.callback, true);
  this.signature = params.signature;
  this.address = params.address;
  this.unsecure = params.unsecure;
  this._uri = !params.uri ? buildURI() : url.parse(params.uri, true);

  function buildURI() {
    var uri = self.callback;
    uri.protocol = SCHEME;
    var params = {};
    params[PARAM_NONCE] = self._nonce;
    if(self.unsecure) params[PARAM_UNSECURE] = 1;
    uri.query = params;
    uri.href = url.format(uri);

    return uri;
  }
}
329376
def litecoin_withdrawal(self, amount, address):
        
        data = {'amount': amount, 'address': address}
        return self._post("ltc_withdrawal/", data=data, return_json=True,
                          version=2)
82683
def send(self, address, data_dict):

        
        if type(address) == list:
            recipients = [self.recipients.get(rec) for rec in address]
        else:
            recipients = [self.recipients.get(address)]

        if recipients:
            for recipient in recipients:
                if recipient:
                    recipient.send(json.dumps(data_dict).encode())
809170
def standard_address(network: nil)
      if public_key_hash_script?
        return BTC::PublicKeyAddress.new(hash: @chunks[2].pushdata, network: network)
      elsif script_hash_script?
        return BTC::ScriptHashAddress.new(hash: @chunks[1].pushdata, network: network)
      elsif public_key_script?
        return BTC::PublicKeyAddress.new(hash: BTC.hash160(@chunks[0].pushdata), network: network)
      end
      nil
    end
1240181
def can_transfer(self):
        
        # 1. The address needs to own the edition
        chain = BlockchainSpider.chain(self._tree, self.edition_number)

        if len(chain) == 0:
            self.reason = 'The edition number {} does not exist in the blockchain'.format(self.edition_number)
            return False

        chain = BlockchainSpider.strip_loan(chain)
        to_address = chain[-1]['to_address']
        if to_address != self.address:
            self.reason = 'Address {} does not own the edition number {}'.format(self.address, self.edition_number)
            return False

        return True
461790
def spendables_for_address(self, address):
        
        URL = self.api_domain + "/unspent?active=%s" % address
        r = json.loads(urlopen(URL).read().decode("utf8"))
        spendables = []
        for u in r["unspent_outputs"]:
            coin_value = u["value"]
            script = h2b(u["script"])
            previous_hash = h2b(u["tx_hash"])
            previous_index = u["tx_output_n"]
            spendables.append(Tx.Spendable(coin_value, script, previous_hash, previous_index))
        return spendables
862707
def dump_all_keys_or_addrs(wallet_obj):
    '''
    
    '''

    print_traversal_warning()

    puts('\nDo you understand this warning?')
    if not confirm(user_prompt=DEFAULT_PROMPT, default=False):
        puts(colored.red('Dump Cancelled!'))
        return

    mpub = wallet_obj.serialize_b58(private=False)

    if wallet_obj.private_key:
        desc_str = 'private keys'
    else:
        desc_str = 'addresses'
        puts('Displaying Public Addresses Only')
        puts('For Private Keys, please open bcwallet with your Master Private Key:\n')
        priv_to_display = '%s123...' % first4mprv_from_mpub(mpub=mpub)
        print_bcwallet_basic_priv_opening(priv_to_display=priv_to_display)

    puts('How many %s (on each chain) do you want to dump?' % desc_str)
    puts('Enter "b" to go back.\n')

    num_keys = get_int(
            user_prompt=DEFAULT_PROMPT,
            max_int=10**5,
            default_input='5',
            show_default=True,
            quit_ok=True,
            )

    if num_keys is False:
        return

    if wallet_obj.private_key:
        print_childprivkey_warning()

    puts('-' * 70)
    for chain_int in (0, 1):
        for current in range(0, num_keys):
            path = "m/%d/%d" % (chain_int, current)
            if current == 0:
                if chain_int == 0:
                    print_external_chain()
                    print_key_path_header()
                elif chain_int == 1:
                    print_internal_chain()
                    print_key_path_header()
            child_wallet = wallet_obj.get_child_for_path(path)
            if wallet_obj.private_key:
                wif_to_use = child_wallet.export_to_wif()
            else:
                wif_to_use = None
            print_path_info(
                    address=child_wallet.to_address(),
                    path=path,
                    wif=wif_to_use,
                    coin_symbol=coin_symbol_from_mkey(mpub),
                    )

    puts(colored.blue('\nYou can compare this output to bip32.org'))
1247377
def _send_to_address(self, address, data, timeout=10):
        
        # Socket to talk to server
        socket = get_context().socket(REQ)
        try:
            socket.setsockopt(LINGER, timeout * 1000)
            if address.find(":") == -1:
                socket.connect("tcp://%s:%d" % (address, self.default_port))
            else:
                socket.connect("tcp://%s" % address)
            socket.send_string(data)
            message = socket.recv_string()
            if message != "ok":
                LOGGER.warn("invalid acknowledge received: %s" % message)

        finally:
            socket.close()
1123038
def make_pay_to_address_outputs(to_address, send_amount, inputs, change_address,
                                fee=STANDARD_FEE):
    
    return [
        # main output
        { "script_hex": make_pay_to_address_script(to_address), "value": send_amount },
        # change output
        { "script_hex": make_pay_to_address_script(change_address),
          "value": calculate_change_amount(inputs, send_amount, fee)
        }
    ]
1342805
def add_address(ipaddress, rule)
      return false unless rule.is_a?(Rule)
      @addresses ||= {}
      (@addresses[ipaddress] ||= []) << rule
      rule
    end
181007
function pickMultipleCoinsAndContinue(){
		conn.query(
			"SELECT unit, message_index, output_index, amount, address, blinding \n\
			FROM outputs \n\
			CROSS JOIN units USING(unit) \n\
			WHERE address IN(?) AND asset"+(asset ? "="+conn.escape(asset) : " IS NULL")+" AND is_spent=0 \n\
				AND sequence='good' "+confirmation_condition+"  \n\
			ORDER BY amount DESC LIMIT ?",
			[arrSpendableAddresses, constants.MAX_INPUTS_PER_PAYMENT_MESSAGE-2],
			function(rows){
				async.eachSeries(
					rows,
					function(row, cb){
						var input = row;
						objectHash.cleanNulls(input);
						required_amount += is_base*TRANSFER_INPUT_SIZE;
						addInput(input);
						// if we allow equality, we might get 0 amount for change which is invalid
						var bFound = is_base ? (total_amount > required_amount) : (total_amount >= required_amount);
						bFound ? cb('found') : cb();
					},
					function(err){
						if (err === 'found')
							onDone(arrInputsWithProofs, total_amount);
						else if (asset)
							issueAsset();
						else
							addHeadersCommissionInputs();
					}
				);
			}
		);
	}
947659
async def create_payment_address(seed: str = None) -> str:
        
        logger = logging.getLogger(__name__)

        if not hasattr(Wallet.create_payment_address, "cb"):
            logger.debug("vcx_wallet_create_payment_address: Creating callback")
            Wallet.create_payment_address.cb = create_cb(CFUNCTYPE(None, c_uint32, c_uint32, c_char_p))

        if seed:
            c_seed = c_char_p(seed.encode('utf-8'))
        else:
            c_seed = None

        result = await do_call('vcx_wallet_create_payment_address',
                               c_seed,
                               Wallet.create_payment_address.cb)

        logger.debug("vcx_wallet_create_payment_address completed")
        return result