Takes a signed transaction hex binary (and coin_symbol) and broadcasts it to the bitcoin network.
504223
def pushtx(tx_hex, coin_symbol='btc', api_key=None):
    '''
    
    '''

    assert is_valid_coin_symbol(coin_symbol)
    assert api_key, 'api_key required'

    url = _get_pushtx_url(coin_symbol=coin_symbol)

    logger.info(url)

    data = {'tx': tx_hex}

    params = {'token': api_key}

    r = requests.post(url, json=data, params=params, verify=True, timeout=TIMEOUT_IN_SECONDS)
    return get_valid_json(r)
1153317
def p2sh_script
      h160 = CoinOp.syncbit(@network[:name]) do
        @native.get_hash160
      end
      self.class.new(blob: Bitcoin::Script.to_p2sh_script(h160), network: @network[:name])
    end
1326662
def sign(ctx, filename):
    
    if filename:
        tx = filename.read()
    else:
        tx = sys.stdin.read()
    tx = TransactionBuilder(eval(tx), bitshares_instance=ctx.bitshares)
    tx.appendMissingSignatures()
    tx.sign()
    print_tx(tx.json())
116794
def sign_singlesig(privkey_hex, plaintext):
    
    hash_hex = hashlib.sha256(plaintext).hexdigest()
    b64sig = virtualchain.ecdsalib.sign_digest(hash_hex, privkey_hex)
    sighex = binascii.hexlify(base64.b64decode(b64sig))
    pubkey_hex = virtualchain.ecdsalib.ecdsa_private_key(privkey_hex).public_key().to_hex()
    return base64.b64encode(virtualchain.btc_script_serialize([sighex, pubkey_hex]).decode('hex'))
1034772
def push(self, tx):
        
        self._service.push_tx(tx)
        return bitcoin.txhash(tx)
217176
def sighash_for_witness(index, script_pubkey_or_script_code, hash_type, amount, skip_separator_index)
      hash_prevouts = Bitcoin.double_sha256(inputs.map{|i|i.out_point.to_payload}.join)
      hash_sequence = Bitcoin.double_sha256(inputs.map{|i|[i.sequence].pack('V')}.join)
      outpoint = inputs[index].out_point.to_payload
      amount = [amount].pack('Q')
      nsequence = [inputs[index].sequence].pack('V')
      hash_outputs = Bitcoin.double_sha256(outputs.map{|o|o.to_payload}.join)

      script_code = script_pubkey_or_script_code.to_script_code(skip_separator_index)

      case (hash_type & 0x1f)
      when SIGHASH_TYPE[:single]
        hash_outputs = index >= outputs.size ? "\x00".ljust(32, "\x00") : Bitcoin.double_sha256(outputs[index].to_payload)
        hash_sequence = "\x00".ljust(32, "\x00")
      when SIGHASH_TYPE[:none]
        hash_sequence = hash_outputs = "\x00".ljust(32, "\x00")
      end

      if (hash_type & SIGHASH_TYPE[:anyonecanpay]) != 0
        hash_prevouts = hash_sequence ="\x00".ljust(32, "\x00")
      end
      hash_type |= (Bitcoin.chain_params.fork_id << 8) if Bitcoin.chain_params.fork_chain?
      buf = [ [version].pack('V'), hash_prevouts, hash_sequence, outpoint,
              script_code ,amount, nsequence, hash_outputs, [@lock_time, hash_type].pack('VV')].join
      Bitcoin.double_sha256(buf)
    end
1109642
public String sign(RawTransaction rawTransaction) {

        byte[] signedMessage;

        if (chainId > ChainId.NONE) {
            signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId, credentials);
        } else {
            signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
        }

        return Numeric.toHexString(signedMessage);
    }
58012
def make_send_to_address_tx(recipient_address, amount, private_key,
        blockchain_client=BlockchainInfoClient(), fee=STANDARD_FEE,
        change_address=None):
    
    # get out the private key object, sending address, and inputs
    private_key_obj, from_address, inputs = analyze_private_key(private_key,
        blockchain_client)
    # get the change address
    if not change_address:
        change_address = from_address
    # create the outputs
    outputs = make_pay_to_address_outputs(recipient_address, amount, inputs,
                                          change_address, fee=fee)
    # serialize the transaction
    unsigned_tx = serialize_transaction(inputs, outputs)

    # generate a scriptSig for each input
    for i in xrange(0, len(inputs)):
        signed_tx = sign_transaction(unsigned_tx, i, private_key_obj.to_hex())
        unsigned_tx = signed_tx

    # return the signed tx
    return signed_tx
1178697
def btc_tx_sighash_segwit(tx, i, prevout_amount, prevout_script, hashcode=SIGHASH_ALL):
    
    txobj = btc_tx_deserialize(tx)

    hash_prevouts = encoding.encode(0, 256, 32)
    hash_sequence = encoding.encode(0, 256, 32)
    hash_outputs = encoding.encode(0, 256, 32)

    if (hashcode & SIGHASH_ANYONECANPAY) == 0:
        prevouts = ''
        for inp in txobj['ins']:
            prevouts += hashing.reverse_hash(inp['outpoint']['hash'])
            prevouts += encoding.encode(inp['outpoint']['index'], 256, 4)[::-1].encode('hex')

        hash_prevouts = hashing.bin_double_sha256(prevouts.decode('hex'))

        # print 'prevouts: {}'.format(prevouts)

    if (hashcode & SIGHASH_ANYONECANPAY) == 0 and (hashcode & 0x1f) != SIGHASH_SINGLE and (hashcode & 0x1f) != SIGHASH_NONE:
        sequences = ''
        for inp in txobj['ins']:
            sequences += encoding.encode(inp['sequence'], 256, 4)[::-1].encode('hex')

        hash_sequence = hashing.bin_double_sha256(sequences.decode('hex'))

        # print 'sequences: {}'.format(sequences)

    if (hashcode & 0x1f) != SIGHASH_SINGLE and (hashcode & 0x1f) != SIGHASH_NONE:
        outputs = ''
        for out in txobj['outs']:
            outputs += encoding.encode(out['value'], 256, 8)[::-1].encode('hex')
            outputs += make_var_string(out['script'])

        hash_outputs = hashing.bin_double_sha256(outputs.decode('hex'))

        # print 'outputs: {}'.format(outputs)

    elif (hashcode & 0x1f) == SIGHASH_SINGLE and i < len(txobj['outs']):
        outputs = ''
        outputs += encoding.encode(txobj['outs'][i]['value'], 256, 8)[::-1].encode('hex')
        outputs += make_var_string(txobj['outs'][i]['script'])

        hash_outputs = hashing.bin_double_sha256(outputs.decode('hex'))

        # print 'outputs: {}'.format(outputs)

    # print 'hash_prevouts: {}'.format(hash_prevouts.encode('hex'))
    # print 'hash_sequence: {}'.format(hash_sequence.encode('hex'))
    # print 'hash_outputs: {}'.format(hash_outputs.encode('hex'))
    # print 'prevout_script: {}'.format(prevout_script)
    # print 'prevout_amount: {}'.format(prevout_amount)

    sighash_preimage = ''
    sighash_preimage += encoding.encode(txobj['version'], 256, 4)[::-1].encode('hex')
    sighash_preimage += hash_prevouts.encode('hex')
    sighash_preimage += hash_sequence.encode('hex')

    # this input's prevout, script, amount, and sequence
    sighash_preimage += hashing.reverse_hash(txobj['ins'][i]['outpoint']['hash'])
    sighash_preimage += encoding.encode(txobj['ins'][i]['outpoint']['index'], 256, 4)[::-1].encode('hex')
    sighash_preimage += make_var_string(prevout_script)
    sighash_preimage += encoding.encode(prevout_amount, 256, 8)[::-1].encode('hex')
    sighash_preimage += encoding.encode(txobj['ins'][i]['sequence'], 256, 4)[::-1].encode('hex')

    sighash_preimage += hash_outputs.encode('hex')
    sighash_preimage += encoding.encode(txobj['locktime'], 256, 4)[::-1].encode('hex')
    sighash_preimage += encoding.encode(hashcode, 256, 4)[::-1].encode('hex')

    sighash = hashing.bin_double_sha256(sighash_preimage.decode('hex')).encode('hex')

    # print 'sighash_preimage: {}'.format(sighash_preimage)
    # print 'sighash: {}'.format(sighash)

    return sighash
639616
def broadcast_transaction(self, hex_tx):
        

        resp = self.obj.sendrawtransaction(hex_tx)
        if len(resp) > 0:
            return {'transaction_hash': resp, 'success': True}
        else:
            return error_reply('Invalid response from bitcoind.')
627527
def btc_make_p2wpkh_address( pubkey_hex ):
    
    pubkey_hex = keylib.key_formatting.compress(pubkey_hex)
    hash160_bin = hashing.bin_hash160(pubkey_hex.decode('hex'))
    return segwit_addr_encode(hash160_bin)
268662
def create_unsigned_transaction(cls,
                                    *,
                                    nonce: int,
                                    gas_price: int,
                                    gas: int,
                                    to: Address,
                                    value: int,
                                    data: bytes) -> 'BaseUnsignedTransaction':
        
        raise NotImplementedError("Must be implemented by subclasses")
797099
def btc_script_hex_to_address( script_hex, segwit=None ):
    
    # TODO: make this support more than bitcoin-like scripts
    if script_hex.startswith("76a914") and script_hex.endswith("88ac") and len(script_hex) == 50:
        # p2pkh script
        hash160_bin = binascii.unhexlify(script_hex[6:-4])
        return bin_hash160_to_address(hash160_bin, version_byte=version_byte)

    elif script_hex.startswith("a914") and script_hex.endswith("87") and len(script_hex) == 46:
        # p2sh script
        hash160_bin = binascii.unhexlify(script_hex[4:-2])
        return bin_hash160_to_address(hash160_bin, version_byte=multisig_version_byte)

    elif script_hex.startswith('0014') and len(script_hex) == 44:
        # p2wpkh script (bech32 address)
        hash160_bin = binascii.unhexlify(script_hex[4:])
        return segwit_addr_encode(hash160_bin) 

    elif script_hex.startswith('0020') and len(script_hex) == 68:
        # p2wsh script (bech32 address)
        sha256_bin = binascii.unhexlify(script_hex[4:])
        return segwit_addr_encode(sha256_bin)

    return None
334938
def send_transaction(
            self,
            to: Address,
            startgas: int,
            value: int = 0,
            data: bytes = b'',
    ) -> bytes:
        
        if to == to_canonical_address(constants.NULL_ADDRESS):
            warnings.warn('For contract creation the empty string must be used.')

        with self._nonce_lock:
            nonce = self._available_nonce
            gas_price = self.gas_price()

            transaction = {
                'data': data,
                'gas': startgas,
                'nonce': nonce,
                'value': value,
                'gasPrice': gas_price,
            }
            node_gas_price = self.web3.eth.gasPrice
            log.debug(
                'Calculated gas price for transaction',
                node=pex(self.address),
                calculated_gas_price=gas_price,
                node_gas_price=node_gas_price,
            )

            # add the to address if not deploying a contract
            if to != b'':
                transaction['to'] = to_checksum_address(to)

            signed_txn = self.web3.eth.account.signTransaction(transaction, self.privkey)

            log_details = {
                'node': pex(self.address),
                'nonce': transaction['nonce'],
                'gasLimit': transaction['gas'],
                'gasPrice': transaction['gasPrice'],
            }
            log.debug('send_raw_transaction called', **log_details)

            tx_hash = self.web3.eth.sendRawTransaction(signed_txn.rawTransaction)
            self._available_nonce += 1

            log.debug('send_raw_transaction returned', tx_hash=encode_hex(tx_hash), **log_details)
            return tx_hash
935344
def p2sh_sig(options)
      string = Script.new(options).to_s
      CoinOp.syncbit(@network[:name]) do
        Bitcoin::Script.binary_from_string("#{string} #{self.to_hex}")
      end
    end
218239
def sign(data)
      sig = @key.dsa_sign_asn1(data)
      if Script::is_low_der_signature?(sig)
        sig
      else
        Bitcoin::OpenSSL_EC.signature_to_low_s(sig)
      end
    end
739825
def send_bitcoin(output: nil, amount: nil, script: nil, address: nil)
      if !output
        raise ArgumentError, "Either `script` or `address` must be specified" if !script && !address
        raise ArgumentError, "Amount must be specified (>= 0)" if (!amount || amount < 0)
        script ||= address.public_address.script if address
        output = TransactionOutput.new(value: amount, script: script)
      end
      self.bitcoin_outputs << output
    end