Store <hexdata> in blockchain and return new txid.
        Utxos taken from <wifs> and change sent to <change_address>.
        <wifs>: '["privatekey_in_wif_format", ...]'
510405
def store_nulldata(self, hexdata, wifs, change_address=None, txouts=None,
                       fee=10000, lock_time=0):
        
        rawtx = self.create_tx(txouts=txouts, lock_time=lock_time)
        rawtx = self.add_nulldata(rawtx, hexdata)
        rawtx = self.add_inputs(rawtx, wifs, change_address=change_address,
                                fee=fee)
        return self.publish(rawtx)
122654
def update_txn_with_extra_data(self, txn):
        
        # For RAW and ENC attributes, only hash is stored in the ledger.
        if get_type(txn) == ATTRIB:
            txn_data = get_payload_data(txn)
            # The key needs to be present and not None
            key = RAW if (RAW in txn_data and txn_data[RAW] is not None) else \
                ENC if (ENC in txn_data and txn_data[ENC] is not None) else None
            if key:
                txn_data[key] = self.attributeStore.get(txn_data[key])
        return txn
729606
def sign_tx(self, rawtx, wifs):
        
        tx = deserialize.tx(rawtx)
        keys = deserialize.keys(self.testnet, wifs)
        tx = control.sign_tx(self.service, self.testnet, tx, keys)
        return serialize.tx(tx)
28826
function getBlockHmac(key, blockIndex, blockLength, blockData) {
    return getHmacKey(key, new Int64(blockIndex)).then(function(blockKey) {
        var blockDataForHash = new Uint8Array(blockData.byteLength + 4 + 8);
        var blockDataForHashView = new DataView(blockDataForHash.buffer);
        blockDataForHash.set(new Uint8Array(blockData), 4 + 8);
        blockDataForHashView.setInt32(0, blockIndex, true);
        blockDataForHashView.setInt32(8, blockLength, true);
        return CryptoEngine.hmacSha256(blockKey, blockDataForHash.buffer);
    });
}
11372
function signTx (tx, privKey) {
  if (!tx.match(/^tx\_.+/)) {
    throw Error('Not a valid transaction')
  }

  const binaryKey = (() => {
    if (program.file) {
      return fs.readFileSync(program.file)
    } else if (privKey) {
      return Buffer.from(privKey, 'hex')
    } else {
      throw Error('Must provide either [privkey] or [file]')
    }
  })()

  const decryptedKey = program.password ? Crypto.decryptKey(program.password, binaryKey) : binaryKey

  // Split the base58Check part of the transaction
  const base58CheckTx = tx.split('_')[1]
  // ... and sign the binary create_contract transaction
  const binaryTx = Crypto.decodeBase58Check(base58CheckTx)

  const signature = Crypto.sign(binaryTx, decryptedKey)

  // the signed tx deserializer expects a 4-tuple:
  // <tag, version, signatures_array, binary_tx>
  const unpackedSignedTx = [
    Buffer.from([11]),
    Buffer.from([1]),
    [Buffer.from(signature)],
    binaryTx
  ]

  console.log(Crypto.encodeTx(unpackedSignedTx))
}
1320618
def privatekey_to_publickey(private_key_bin: bytes) -> bytes:
    
    if not ishash(private_key_bin):
        raise ValueError('private_key_bin format mismatch. maybe hex encoded?')
    return keys.PrivateKey(private_key_bin).public_key.to_bytes()
720409
def get_private_key_from_wif(wif: str) -> bytes:
        
        if wif is None or wif is "":
            raise Exception("none wif")
        data = base58.b58decode(wif)
        if len(data) != 38 or data[0] != 0x80 or data[33] != 0x01:
            raise Exception("wif wrong")
        checksum = Digest.hash256(data[0:34])
        for i in range(4):
            if data[len(data) - 4 + i] != checksum[i]:
                raise Exception("wif wrong")
        return data[1:33]
910040
def make_op_return_tx(data, private_key,
        blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE,
        change_address=None, format='bin'):
    
    # 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_op_return_outputs(data, inputs, change_address,
        fee=fee, format=format)
    # 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
176070
def generate_keypair(crypto, seed, password=None):
    
    if crypto in ['eth', 'etc']:
        raise CurrencyNotSupported("Ethereums not yet supported")

    pub_byte, priv_byte = get_magic_bytes(crypto)
    priv = sha256(seed)
    pub = privtopub(priv)

    priv_wif = encode_privkey(priv, 'wif_compressed', vbyte=priv_byte)
    if password:
        # pycrypto etc. must be installed or this will raise ImportError, hence inline import.
        from .bip38 import Bip38EncryptedPrivateKey
        priv_wif = str(Bip38EncryptedPrivateKey.encrypt(crypto, priv_wif, password))

    compressed_pub = encode_pubkey(pub, 'hex_compressed')
    ret = {
        'public': {
            'hex_uncompressed': pub,
            'hex': compressed_pub,
            'address': pubtoaddr(compressed_pub, pub_byte)
        },
        'private': {
            'wif': priv_wif
        }
    }
    if not password:
        # only these are valid when no bip38 password is supplied
        ret['private']['hex'] = encode_privkey(priv, 'hex_compressed', vbyte=priv_byte)
        ret['private']['hex_uncompressed'] = encode_privkey(priv, 'hex', vbyte=priv_byte)
        ret['private']['wif_uncompressed'] = encode_privkey(priv, 'wif', vbyte=priv_byte)

    return ret
322178
def add_inputs(self, rawtx, wifs, change_address=None, fee=10000,
                   dont_sign=False):
        
        tx = deserialize.tx(rawtx)
        keys = deserialize.keys(self.testnet, wifs)
        fee = deserialize.positive_integer(fee)
        if change_address is not None:
            change_address = deserialize.address(self.testnet, change_address)
        tx = control.add_inputs(self.service, self.testnet, tx, keys,
                                change_address=change_address, fee=fee)

        if not dont_sign:
            tx = control.sign_tx(self.service, self.testnet, tx, keys)

        return serialize.tx(tx)
1282026
def btc_tx_sign_multisig_segwit(tx, idx, prevout_amount, witness_script, private_keys, hashcode=SIGHASH_ALL, hashcodes=None, native=False):
    

    from .multisig import parse_multisig_redeemscript

    if hashcodes is None:
        hashcodes = [hashcode] * len(private_keys)

    txobj = btc_tx_deserialize(str(tx))
    privs = {}
    for pk in private_keys:
        pubk = ecdsalib.ecdsa_private_key(pk).public_key().to_hex()

        compressed_pubkey = keylib.key_formatting.compress(pubk)
        privs[compressed_pubkey] = pk

    m, public_keys = parse_multisig_redeemscript(witness_script)

    used_keys, sigs = [], []
    for i, public_key in enumerate(public_keys):
        if public_key not in privs:
            continue

        if len(used_keys) == m:
            break

        if public_key in used_keys:
            raise ValueError('Tried to reuse key in witness script: {}'.format(public_key))

        pk_str = privs[public_key]
        used_keys.append(public_key)

        sig = btc_tx_make_input_signature_segwit(tx, idx, prevout_amount, witness_script, pk_str, hashcodes[i])
        sigs.append(sig)

        # print ''

    if len(used_keys) != m:
        raise ValueError('Missing private keys (used {}, required {})'.format(len(used_keys), m))
   
    if native: 
        # native p2wsh
        txobj['ins'][idx]['witness_script'] = btc_witness_script_serialize([None] + sigs + [witness_script]) 

        # print 'segwit multisig: native p2wsh: witness script {}'.format(txobj['ins'][idx]['witness_script'])

    else:
        # p2sh-p2wsh
        redeem_script = btc_make_p2sh_p2wsh_redeem_script(witness_script)
        txobj['ins'][idx]['script'] = redeem_script
        txobj['ins'][idx]['witness_script'] = btc_witness_script_serialize([None] + sigs + [witness_script]) 
        
        # print 'segwit multisig: p2sh p2wsh: witness script {}'.format(txobj['ins'][idx]['witness_script'])
        # print 'segwit multisig: p2sh p2wsh: redeem script {}'.format(txobj['ins'][idx]['script'])
    
    return btc_tx_serialize(txobj)
935699
private function decodeWIF($WIF_encoded_key)
    {
        /* Using the Base58 decoding function and remove the padding. */
        $decoded_key = $this->stripHexPrefix($this->decodeBase58(trim($WIF_encoded_key)));

        list($private_key, $checksum_provided) = array(
                                                       substr($decoded_key, 0, -8), 
                                                       substr($decoded_key, strlen($decoded_key) - 8)
                                                       );

        $private_key_type = substr($private_key, 0, 2);

        if ($private_key_type != '80' && $private_key_type != 'ef') {
            throw new \Exception('Invalid WIF encoded private key! Network type was not present in value provided. Checked ' . $private_key . ' and found ' . $private_key_type);
        }

        $private_key           = substr($private_key, 2);
        $compressed_public_key = (substr($private_key, strlen($private_key) - 2) == '01') ? '01' : '';
        $private_key           = ($compressed_public_key == '01') ? substr($private_key, 0, -2) : $private_key;

        /* Now let's check our private key against the checksum provided. */
        $new_checksum = substr(hash('sha256', hash('sha256', $this->binConv($private_key_type . $private_key . $compressed_public_key), true)), 0, 8);

        if ($new_checksum != $checksum_provided) {
            throw new \Exception('Invalid WIF encoded private key! Checksum is incorrect! Value encoded with key was: ' . $checksum_provided . ' but this does not match the recalculated value of: ' . $new_checksum . ' from the decoded provided value of: ' . $decoded_key);
        }

        return $private_key;
    }
89795
function TXDBState(wid, id) {
  this.wid = wid;
  this.id = id;
  this.tx = 0;
  this.coin = 0;
  this.unconfirmed = 0;
  this.confirmed = 0;
  this.committed = false;
}
1185494
def build

      if !self.change_address
        raise MissingChangeAddressError
      end

      result = Result.new

      add_input_for_utxo = proc do |utxo|
        raise ArgumentError, "Unspent output must contain index" if !utxo.index
        raise ArgumentError, "Unspent output must contain transaction_hash" if !utxo.transaction_hash

        if !self.internal_provider.consumed_unspent_output?(utxo)
          self.internal_provider.consume_unspent_output(utxo)

          result.inputs_amount += utxo.value
          txin = TransactionInput.new(
                                      previous_hash: utxo.transaction_hash,
                                      previous_index: utxo.index,
                                      # put the output script here so the signer knows which key to use.
                                      signature_script: utxo.script)
          txin.transaction_output = utxo
          result.transaction.add_input(txin)
        else
          # UTXO was already consumed possibly by another Tx Builder sharing the same provider.
        end
      end

      # If no outputs are specified, spend all utxos to a change address, minus the mining fee.
      if (self.outputs || []).size == 0
        result.inputs_amount = 0

        (self.prepended_unspent_outputs || []).each(&add_input_for_utxo)
        (self.unspent_outputs || []).each(&add_input_for_utxo)

        if result.transaction.inputs.size == 0
          raise MissingUnspentOutputsError, "Missing unspent outputs"
        end

        # Value will be determined after computing the fee
        change_output = TransactionOutput.new(value: 0, script: self.change_address.public_address.script)
        result.transaction.add_output(change_output)

        result.fee = compute_fee_for_transaction(result.transaction, self.fee_rate)
        result.outputs_amount = result.inputs_amount - result.fee
        result.change_amount = 0

        # Check if inputs cover the fees
        if result.outputs_amount < 0
          raise InsufficientFundsError.new(result)
        end

        # Warn if the output amount is relatively small.
        if result.outputs_amount < result.fee
          Diagnostics.current.add_message("BTC::TransactionBuilder: Warning! Spending all unspent outputs returns less than a mining fee. (#{result.outputs_amount} < #{result.fee})")
        end

        # Set the output value as needed
        result.transaction.outputs[0].value = result.outputs_amount

        # For each address that is a WIF, locate the matching input and sign it.
        attempt_to_sign_transaction(result)

        return result
      end # if no specific outputs required

      # We are having one or more outputs (e.g. normal payment)
      # Need to find appropriate unspents and compose a transaction.

      # Prepare all outputs.
      # result.outputs_amount will also contain a fee after it's calculated.
      (self.outputs || []).each do |txout|
        result.outputs_amount += txout.value
        result.transaction.add_output(txout)
      end

      # We'll determine final change value depending on inputs.
      # Setting default to MAX_MONEY will protect against a bug when we fail to update the amount and
      # spend unexpected amount on mining fees.
      change_output = TransactionOutput.new(value: MAX_MONEY, script: self.change_address.public_address.script)
      result.transaction.add_output(change_output)

      mandatory_utxos = (self.prepended_unspent_outputs || []).to_a.dup

      # We have specific outputs with specific amounts, so we need to select the best amount of coins.
      # To play nice with BIP32/BIP44 change addresses (that need to monitor an increasing amount of addresses),
      # we'll spend oldest outputs first and will add more and more newer outputs until we cover fees
      # and change output is either zero or above the dust limit.
      # If `confirmations` attribute is nil, order is preserved.
      utxos = self.unspent_outputs || []
      if self.keep_unspent_outputs_order
        sorted_utxos = utxos.to_a.dup
      else
        sorted_utxos = utxos.to_a.sort_by{|txout| -(txout.confirmations || -1) } # oldest first
      end
      
      if self.parent_transactions
        # Can repeat some outputs in mandatory_utxos or sorted_utxos, 
        # but double-spending will be prevented by provider.
        self.parent_transactions.each do |parenttx|
          sorted_utxos += parenttx.outputs
        end
      end
      
      all_utxos = (sorted_utxos + mandatory_utxos)

      while true
        if (sorted_utxos.size + mandatory_utxos.size) == 0
          raise InsufficientFundsError.new(result)
        end

        utxo = nil
        while (sorted_utxos.size + mandatory_utxos.size) > 0
          utxo = if mandatory_utxos.size > 0
            mandatory_utxos.shift
          else
            sorted_utxos.shift
          end 
          if utxo.value > 0 &&
            !utxo.script.op_return_script? &&
            !self.internal_provider.consumed_unspent_output?(utxo)
            self.internal_provider.consume_unspent_output(utxo)
            break
          else
            #puts "CONSUMED UTXO, SKIPPING: #{utxo.transaction_id}:#{utxo.index} (#{utxo.value})"
            # Continue reading utxos to find one that is not consumed yet.
            utxo = nil
          end
        end
        
        if !utxo
          # puts "ALL UTXOS:"
          # all_utxos.each do |utxo|
          #   puts "--> #{utxo.transaction_id}:#{utxo.index} (#{utxo.value})"
          # end
          raise InsufficientFundsError
        end
        
        result.inputs_amount += utxo.value

        raise ArgumentError, "Transaction hash must be non-nil in unspent output" if !utxo.transaction_hash
        raise ArgumentError, "Index must be non-nil in unspent output" if !utxo.index

        txin = TransactionInput.new(previous_hash: utxo.transaction_hash,
                                    previous_index: utxo.index,
                                    # put the output script here so the signer knows which key to use.
                                    signature_script: utxo.script)
        txin.transaction_output = utxo
        result.transaction.add_input(txin)

        # Do not check the result before we included all the mandatory utxos.
        if mandatory_utxos.size == 0
          # Before computing the fee, quick check if we have enough inputs to cover the outputs.
          # If not, go and add one more utxo before wasting time computing fees.
          if result.inputs_amount >= result.outputs_amount
            fee = compute_fee_for_transaction(result.transaction, self.fee_rate)

            change = result.inputs_amount - result.outputs_amount - fee

            if change >= self.minimum_change

              # We have a big enough change, set missing values and return.

              change_output.value = change
              result.change_amount = change
              result.outputs_amount += change
              result.fee = fee
              attempt_to_sign_transaction(result)
              return result

            elsif change > self.dust_change && change < self.minimum_change

              # We have a shitty change: not small enough to forgo, not big enough to be useful.
              # Try adding more utxos on the next cycle (or fail if no more utxos are available).

            elsif change >= 0 && change <= self.dust_change
              # This also includes the case when change is exactly zero satoshis.
              # Remove the change output, keep existing outputs_amount, set fee and try to sign.
              result.transaction.outputs = result.transaction.outputs[0, result.transaction.outputs.size - 1]
              result.change_amount = 0
              result.fee = fee
              attempt_to_sign_transaction(result)
              return result

            else
              # Change is negative, we need more funds for this transaction.
              # Try adding more utxos on the next cycle.
              result.fee = fee
            end

          end # if inputs_amount >= outputs_amount
        end # if no more mandatory outputs to add
      end # while true
    end
960670
def PrivateKeyFromWIF(wif):
        
        if wif is None or len(wif) is not 52:
            raise ValueError('Please provide a wif with a length of 52 bytes (LEN: {0:d})'.format(len(wif)))

        data = base58.b58decode(wif)

        length = len(data)

        if length is not 38 or data[0] is not 0x80 or data[33] is not 0x01:
            raise ValueError("Invalid format!")

        checksum = Crypto.Hash256(data[0:34])[0:4]

        if checksum != data[34:]:
            raise ValueError("Invalid WIF Checksum!")

        return data[1:33]
196224
function ECKeySign(hashBytes, priKeyBytes) {
  let ec = new EC('secp256k1');
  let key = ec.keyFromPrivate(priKeyBytes, 'bytes');
  let signature = key.sign(hashBytes);
  let r = signature.r;
  let s = signature.s;
  let id = signature.recoveryParam;
  let rHex = r.toString('hex');
  while (rHex.length < 64) {
    rHex = "0" + rHex;
  }
  let sHex = s.toString('hex');
  while (sHex.length < 64) {
    sHex = "0" + sHex;
  }
  let idHex = byte2hexStr(id);
  let signHex = rHex + sHex + idHex;
  return hexStr2byteArray(signHex);
}
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'))