/*
Signature hashing for TXOBJ
@param {String} address
@param {Number} i, which transaction input to sign
@param {String} hex string of script
@param {String} hash code (SIGHASH_ALL, SIGHASH_NONE...)
return {String} output script
351079
function signatureForm(txObj, i, script, hashcode) {
  // Copy object so we don't rewrite it
  var newTx = JSON.parse(JSON.stringify(txObj));

  for (var j = 0; j < newTx.ins.length; j++) {
    newTx.ins[j].script = '';
  }
  newTx.ins[i].script = script;

  if (hashcode === zconstants.SIGHASH_NONE) {
    newTx.outs = [];
  } else if (hashcode === zconstants.SIGHASH_SINGLE) {
    newTx.outs = newTx.outs.slice(0, newTx.ins.length);
    for (var j = 0; j < newTx.ins.length - 1; ++j) {
      newTx.outs[j].satoshis = Math.pow(2, 64) - 1;
      newTx.outs[j].script = '';
    }
  } else if (hashcode === zconstants.SIGHASH_ANYONECANPAY) {
    newTx.ins = [newTx.ins[i]];
  }

  return newTx;
}
1096814
function (hash) {
            var iframe = this._iframe;
            if (!iframe) {
                return;
            }
            hash = hash || "";
            if (this._currentIframeHashString != hash) {
                var src = ['javascript:document.open();'];
                src.push('document.write(\"<script type=\\\"text/javascript\\\">');
                if (Aria.domain) {
                    src.push('document.domain=\\\"' + Aria.domain + '\\\";');
                }
                src.push('if (parent.' + this.$classpath + '){parent.' + this.$classpath
                        + '.polledIframeHashString=\\\"' + hash + '\\\";}');
                src.push("</script>\");");
                src.push('document.close();');
                iframe.src = src.join("");
                this._currentIframeHashString = hash;
            }
        }
242761
def _sighash_final_hashing(self, copy_tx, sighash_type):
        '''
        
        '''
        sighash = ByteData()
        sighash += copy_tx.to_bytes()
        sighash += utils.i2le_padded(sighash_type, 4)

        return utils.hash256(sighash.to_bytes())
1046231
def parse_issuance_p2sh_pointer(script_sig)
      script = Bitcoin::Script.new(script_sig).chunks.last
      redeem_script = Bitcoin::Script.new(script)
      return nil unless redeem_script.chunks[1] == Bitcoin::Script::OP_DROP
      asset_def = to_bytes(redeem_script.chunks[0].to_s.bth)[0..-1].map{|x|x.to_i(16).chr}.join
      asset_def && asset_def.start_with?('u=') ? asset_def : nil
    end
505516
private static HashCode sign(Operation value) {
    Hasher h = Hashing.md5().newHasher();
    h.putString(value.getConsumerId(), StandardCharsets.UTF_8);
    h.putChar('\0');
    h.putString(value.getOperationName(), StandardCharsets.UTF_8);
    h.putChar('\0');
    return Signing.putLabels(h, value.getLabels()).hash();
  }
1023945
def sighash_all(self, index, script=None, anyone_can_pay=False):
        '''
        
        '''
        copy_tx = self._sighash_prep(index, script)

        if anyone_can_pay:
            return self._sighash_anyone_can_pay(
                index=index,
                copy_tx=copy_tx,
                sighash_type=shared.SIGHASH_ALL)

        return self._sighash_final_hashing(
            index=index,
            copy_tx=copy_tx,
            sighash_type=shared.SIGHASH_ALL)
844108
function checkShash(i) {
  const start = i;
  let l;

  if (i >= tokensLength) return 0;

  if (tokens[i].type === TokenType.NumberSign) i++;
  else return 0;

  if (l = checkIdentOrInterpolation(i) || checkPartialIdent(i)) i += l;
  else return 0;

  while (i < tokensLength) {
    if (l = checkIdentOrInterpolation(i) || checkPartialIdent(i)) i += l;
    else break;
  }

  tokens[start].shashEnd = i;

  return i - start;
}
765250
def SignMessage(self, message, script_hash):
        

        keypair = self.GetKeyByScriptHash(script_hash)
        prikey = bytes(keypair.PrivateKey)
        res = Crypto.Default().Sign(message, prikey)
        return res, keypair.PublicKey
47138
def _hash_sequence(self, sighash_type, anyone_can_pay):
        '''
        '''
        if anyone_can_pay or sighash_type == shared.SIGHASH_SINGLE:
            # If any of ANYONECANPAY, SINGLE sighash type is set,
            # hashSequence is a uint256 of 0x0000......0000.
            return b'\x00' * 32
        else:
            # hashSequence is the double SHA256 of nSequence of all inputs;
            sequences = ByteData()
            for tx_in in self.tx_ins:
                sequences += tx_in.sequence
            return utils.hash256(sequences.to_bytes())
172481
def hash_input(inpt, algo=HASH_SHA256):
    """"""
    if (algo == HASH_MD5):
        hashcode = hashlib.md5()
    elif (algo == HASH_SHA1):
        hashcode = hashlib.sha1()
    elif (algo == HASH_SHA224):
        hashcode = hashlib.sha224()
    elif (algo == HASH_SHA256):
        hashcode = hashlib.sha256()
    elif (algo == HASH_SHA384):
        hashcode = hashlib.sha384()
    elif (algo == HASH_SHA512):
        hashcode = hashlib.sha512()

    if sys.version_info.major == 2:
        inpt = bytes(inpt)
    else:
        inpt = bytes(inpt, "utf-8")

    hashcode.update(inpt)
    hexhash = hashcode.hexdigest()
    return hexhash
649463
function hash(sess) {
  // serialize
  var str = JSON.stringify(sess, function (key, val) {
    // ignore sess.cookie property
    if (this === sess && key === 'cookie') {
      return
    }

    return val
  })

  // hash
  return crypto
    .createHash('sha1')
    .update(str, 'utf8')
    .digest('hex')
}
59717
def btc_tx_sign_input(tx, idx, prevout_script, prevout_amount, private_key_info, hashcode=SIGHASH_ALL, hashcodes=None, segwit=None, scriptsig_type=None, redeem_script=None, witness_script=None, **blockchain_opts):
    
    if segwit is None:
        segwit = get_features('segwit')
    
    if scriptsig_type is None:
        scriptsig_type = btc_privkey_scriptsig_classify(private_key_info)
    
    if scriptsig_type in ['p2wpkh', 'p2wsh', 'p2sh-p2wpkh', 'p2sh-p2wsh'] and not segwit:
        raise ValueError("Segwit is not enabled, but {} is a segwit scriptsig type".format(prevout_script))

    return btc_tx_sign(tx, idx, prevout_script, prevout_amount, private_key_info, scriptsig_type, hashcode=hashcode, hashcodes=hashcodes, redeem_script=redeem_script, witness_script=witness_script)
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
461229
def address_to_scripthash(address: str) -> UInt160:
    """"""
    AddressVersion = 23  # fixed at this point
    data = b58decode(address)
    if len(data) != 25:
        raise ValueError('Not correct Address, wrong length.')
    if data[0] != AddressVersion:
        raise ValueError('Not correct Coin Version')

    checksum_data = data[:21]
    checksum = hashlib.sha256(hashlib.sha256(checksum_data).digest()).digest()[:4]
    if checksum != data[21:]:
        raise Exception('Address format error')
    return UInt160(data=data[1:21])
1005988
def btc_tx_make_input_signature_segwit(tx, idx, prevout_amount, prevout_script, privkey_str, hashcode):
    
    # always compressed
    if len(privkey_str) == 64:
        privkey_str += '01'

    pk = ecdsalib.ecdsa_private_key(str(privkey_str))
    pubk = pk.public_key()
    
    priv = pk.to_hex()

    # must always be compressed
    pub = keylib.key_formatting.compress(pubk.to_hex())
    sighash = btc_tx_sighash_segwit(tx, idx, prevout_amount, prevout_script, hashcode=hashcode)
    
    # sign using uncompressed private key
    # pk_uncompressed_hex, pubk_uncompressed_hex = ecdsalib.get_uncompressed_private_and_public_keys(priv)
    sigb64 = ecdsalib.sign_digest( sighash, priv )

    # sanity check 
    # assert ecdsalib.verify_digest( txhash, pubk_uncompressed_hex, sigb64 )

    sig_r, sig_s = ecdsalib.decode_signature(sigb64)
    sig_bin = btc_tx_der_encode_signature(sig_r, sig_s)
    sig = sig_bin.encode('hex') + encoding.encode(hashcode, 16, 2)

    # print 'segwit signature: {}'.format(sig)
    return sig
843284
def to_output_script(address):
    '''
    
    '''
    parsed = parse(address)
    parsed_hash = b''

    try:
        if (parsed.find(riemann.network.P2WPKH_PREFIX) == 0
                and len(parsed) == 22):
            return parsed
    except TypeError:
        pass

    try:
        if (parsed.find(riemann.network.P2WSH_PREFIX) == 0
                and len(parsed) == 34):
            return parsed
    except TypeError:
        pass

    try:
        if (parsed.find(riemann.network.CASHADDR_P2SH) == 0
                and len(parsed) == len(riemann.network.CASHADDR_P2SH) + 20):
            prefix = b'\xa9\x14'  # OP_HASH160 PUSH14
            parsed_hash = parsed[len(riemann.network.P2SH_PREFIX):]
            suffix = b'\x87'  # OP_EQUAL
    except TypeError:
        pass

    try:
        if (parsed.find(riemann.network.CASHADDR_P2PKH) == 0
                and len(parsed) == len(riemann.network.CASHADDR_P2PKH) + 20):
            prefix = b'\x76\xa9\x14'  # OP_DUP OP_HASH160 PUSH14
            parsed_hash = parsed[len(riemann.network.P2PKH_PREFIX):]
            suffix = b'\x88\xac'  # OP_EQUALVERIFY OP_CHECKSIG
    except TypeError:
        pass

    if (parsed.find(riemann.network.P2PKH_PREFIX) == 0
            and len(parsed) == len(riemann.network.P2PKH_PREFIX) + 20):
        prefix = b'\x76\xa9\x14'  # OP_DUP OP_HASH160 PUSH14
        parsed_hash = parsed[len(riemann.network.P2PKH_PREFIX):]
        suffix = b'\x88\xac'  # OP_EQUALVERIFY OP_CHECKSIG

    if (parsed.find(riemann.network.P2SH_PREFIX) == 0
            and len(parsed) == len(riemann.network.P2SH_PREFIX) + 20):
        prefix = b'\xa9\x14'  # OP_HASH160 PUSH14
        parsed_hash = parsed[len(riemann.network.P2SH_PREFIX):]
        suffix = b'\x87'  # OP_EQUAL

    if parsed_hash == b'':
        raise ValueError('Cannot parse output script from address.')

    output_script = prefix + parsed_hash + suffix
    return output_script
421277
public ECDSASignature sign(byte[] transactionHash) {
        ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));

        ECPrivateKeyParameters privKey = new ECPrivateKeyParameters(privateKey, Sign.CURVE);
        signer.init(true, privKey);
        BigInteger[] components = signer.generateSignature(transactionHash);

        return new ECDSASignature(components[0], components[1]).toCanonicalised();
    }