p2sh embedding p2pkh
346677
def p2sh_p2pkh_script(network: str, address: str) -> P2shScript:
    ''''''

    network_params = net_query(network)

    addr = Address.from_string(network=network_params,
                               string=address)

    p2pkh = P2pkhScript(addr)

    return P2shScript(p2pkh)
619632
def _hash_to_sh_address(script_hash, witness=False, cashaddr=True):
    '''
    
    '''
    addr_bytes = bytearray()
    if riemann.network.CASHADDR_P2SH is not None and cashaddr:
        addr_bytes.extend(riemann.network.CASHADDR_P2SH)
        addr_bytes.extend(script_hash)
        return riemann.network.CASHADDR_ENCODER.encode(addr_bytes)
    if witness:
        addr_bytes.extend(riemann.network.P2WSH_PREFIX)
        addr_bytes.extend(script_hash)
        return riemann.network.SEGWIT_ENCODER.encode(addr_bytes)
    else:
        addr_bytes.extend(riemann.network.P2SH_PREFIX)
        addr_bytes.extend(script_hash)
        return riemann.network.LEGACY_ENCODER.encode(addr_bytes)
1249112
def hexlify_pbkdf2(password, salt, iterations, length, digest=hashlib.sha1):
    
    # log.debug("hexlify_pbkdf2 with iterations=%i", iterations)
    hash = crypto.pbkdf2(password, salt, iterations=iterations, dklen=length, digest=digest)
    hash = binascii.hexlify(hash)
    hash = six.text_type(hash, "ascii")
    return hash
604168
def _hash_pair(first: bytes, second: bytes) -> bytes:
    
    if first is None:
        return second

    if second is None:
        return first

    if first > second:
        return keccak(second + first)
    else:
        return keccak(first + second)
887843
def make_pkh_address(pubkey, witness=False, cashaddr=True):
    '''
    
    '''
    pubkey_hash = utils.hash160(pubkey)
    return _make_pkh_address(pubkey_hash=pubkey_hash,
                             witness=witness,
                             cashaddr=cashaddr)
1276015
def make_pkh_output_script(pubkey, witness=False):
    '''
    
    '''
    if witness and not riemann.network.SEGWIT:
        raise ValueError(
            'Network {} does not support witness scripts.'
            .format(riemann.get_current_network_name()))

    output_script = bytearray()

    if type(pubkey) is not bytearray and type(pubkey) is not bytes:
        raise ValueError('Unknown pubkey format. '
                         'Expected bytes. Got: {}'.format(type(pubkey)))

    pubkey_hash = utils.hash160(pubkey)

    if witness:
        output_script.extend(riemann.network.P2WPKH_PREFIX)
        output_script.extend(pubkey_hash)
    else:
        output_script.extend(b'\x76\xa9\x14')  # OP_DUP OP_HASH160 PUSH14
        output_script.extend(pubkey_hash)
        output_script.extend(b'\x88\xac')  # OP_EQUALVERIFY OP_CHECKSIG
    return output_script
1307136
def encrypt_password(password, salt, hash)
      case hash.to_s
      when 'sha256'
        Digest::SHA256.hexdigest("#{password}-#{salt}")
      else
        raise 'Unsupported hash algorithm'
      end
    end
161510
def make_pkh_output(value, pubkey, witness=False):
    '''
    
    '''
    return _make_output(
        value=utils.i2le_padded(value, 8),
        output_script=make_pkh_output_script(pubkey, witness))
32527
function hashpw(password, salt, callback, progress) {
    var real_salt;
    var passwordb = [];
    var saltb = [];
    var hashed = [];
    var minor = String.fromCharCode(0);
    var rounds = 0;
    var off = 0;

    if (!progress) {
        progress = function() {};
    }

    if (salt.charAt(0) != '$' || salt.charAt(1) != '2')
        throw "Invalid salt version";
    if (salt.charAt(2) == '$')
        off = 3;
    else {
        minor = salt.charAt(2);
        if ((minor != 'a' && minor != 'b') || salt.charAt(3) != '$')
            throw "Invalid salt revision";
        off = 4;
    }

    // Extract number of rounds
    if (salt.charAt(off + 2) > '$')
        throw "Missing salt rounds";
    var r1 = parseInt(salt.substring(off, off + 1)) * 10;
    var r2 = parseInt(salt.substring(off + 1, off + 2));
    rounds = r1 + r2;
    real_salt = salt.substring(off + 3, off + 25);
    password = password + (minor >= 'a' ? "\000" : "");
    passwordb = password_to_bytes(password)
    saltb = decode_base64(real_salt, BCRYPT_SALT_LEN);
    crypt_raw(
        passwordb,
        saltb,
        rounds,
        BF_CRYPT_CIPHERTEXT.slice(0),
        function(hashed) {
            var rs = [];
            rs.push("$2");
            if (minor >= 'a')
                rs.push(minor);
            rs.push("$");
            if (rounds < 10)
                rs.push("0");
            rs.push(rounds.toString());
            rs.push("$");
            rs.push(encode_base64(saltb, saltb.length));
            rs.push(encode_base64(hashed, BF_CRYPT_CIPHERTEXT.length * 4 - 1));
            callback(rs.join(''));
        },
        progress);
}
421614
def p2pkh(self, s):
        
        data = self.parse_b58_hashed(s)
        if data is None or not data.startswith(self._address_prefix):
            return None
        size = len(self._address_prefix)
        script = self._network.contract.for_p2pkh(data[size:])
        script_info = self._network.contract.info_for_script(script)
        return Contract(script_info, self._network)
229284
def sshfp_data(key_t, hash_t, pub):
    '''
    
    '''
    key_t = RFC.validate(key_t, RFC.SSHFP_ALGO, 'in')
    hash_t = RFC.validate(hash_t, RFC.SSHFP_HASH)

    hasher = hashlib.new(hash_t)
    hasher.update(
        base64.b64decode(pub)
    )
    ssh_fp = hasher.hexdigest()

    return _rec2data(key_t, hash_t, ssh_fp)
1354700
function scrypt(password, salt, N, r, p, dkLen, callback) {

        if (!callback) { throw new Error('missing callback'); }

        N = ensureInteger(N, 'N');
        r = ensureInteger(r, 'r');
        p = ensureInteger(p, 'p');

        dkLen = ensureInteger(dkLen, 'dkLen');

        if (N === 0 || (N & (N - 1)) !== 0) { throw new Error('N must be power of 2'); }

        if (N > MAX_VALUE / 128 / r) { throw new Error('N too large'); }
        if (r > MAX_VALUE / 128 / p) { throw new Error('r too large'); }

        if (!checkBufferish(password)) {
            throw new Error('password must be an array or buffer');
        }
        password = Array.prototype.slice.call(password);

        if (!checkBufferish(salt)) {
            throw new Error('salt must be an array or buffer');
        }
        salt = Array.prototype.slice.call(salt);

        var b = PBKDF2_HMAC_SHA256_OneIter(password, salt, p * 128 * r);
        var B = new Uint32Array(p * 32 * r)
        for (var i = 0; i < B.length; i++) {
            var j = i * 4;
            B[i] = ((b[j + 3] & 0xff) << 24) |
                   ((b[j + 2] & 0xff) << 16) |
                   ((b[j + 1] & 0xff) << 8) |
                   ((b[j + 0] & 0xff) << 0);
        }

        var XY = new Uint32Array(64 * r);
        var V = new Uint32Array(32 * r * N);

        var Yi = 32 * r;

        // scratch space
        var x = new Uint32Array(16);       // salsa20_8
        var _X = new Uint32Array(16);      // blockmix_salsa8

        var totalOps = p * N * 2;
        var currentOp = 0;
        var lastPercent10 = null;

        // Set this to true to abandon the scrypt on the next step
        var stop = false;

        // State information
        var state = 0;
        var i0 = 0, i1;
        var Bi;

        // How many blockmix_salsa8 can we do per step?
        var limit = parseInt(1000 / r);

        // Trick from scrypt-async; if there is a setImmediate shim in place, use it
        var nextTick = (typeof(setImmediate) !== 'undefined') ? setImmediate : setTimeout;

        // This is really all I changed; making scryptsy a state machine so we occasionally
        // stop and give other evnts on the evnt loop a chance to run. ~RicMoo
        var incrementalSMix = function() {
            if (stop) {
                return callback(new Error('cancelled'), currentOp / totalOps);
            }

            switch (state) {
                case 0:
                    // for (var i = 0; i < p; i++)...
                    Bi = i0 * 32 * r;

                    arraycopy(B, Bi, XY, 0, Yi);                       // ROMix - 1

                    state = 1;                                         // Move to ROMix 2
                    i1 = 0;

                    // Fall through

                case 1:

                    // Run up to 1000 steps of the first inner smix loop
                    var steps = N - i1;
                    if (steps > limit) { steps = limit; }
                    for (var i = 0; i < steps; i++) {                  // ROMix - 2
                        arraycopy(XY, 0, V, (i1 + i) * Yi, Yi)         // ROMix - 3
                        blockmix_salsa8(XY, Yi, r, x, _X);             // ROMix - 4
                    }

                    // for (var i = 0; i < N; i++)
                    i1 += steps;
                    currentOp += steps;

                    // Call the callback with the progress (optionally stopping us)
                    var percent10 = parseInt(1000 * currentOp / totalOps);
                    if (percent10 !== lastPercent10) {
                        stop = callback(null, currentOp / totalOps);
                        if (stop) { break; }
                        lastPercent10 = percent10;
                    }

                    if (i1 < N) {
                        break;
                    }

                    i1 = 0;                                          // Move to ROMix 6
                    state = 2;

                    // Fall through

                case 2:

                    // Run up to 1000 steps of the second inner smix loop
                    var steps = N - i1;
                    if (steps > limit) { steps = limit; }
                    for (var i = 0; i < steps; i++) {                // ROMix - 6
                        var offset = (2 * r - 1) * 16;               // ROMix - 7
                        var j = XY[offset] & (N - 1);
                        blockxor(V, j * Yi, XY, Yi);                 // ROMix - 8 (inner)
                        blockmix_salsa8(XY, Yi, r, x, _X);           // ROMix - 9 (outer)
                    }

                    // for (var i = 0; i < N; i++)...
                    i1 += steps;
                    currentOp += steps;

                    // Call the callback with the progress (optionally stopping us)
                    var percent10 = parseInt(1000 * currentOp / totalOps);
                    if (percent10 !== lastPercent10) {
                        stop = callback(null, currentOp / totalOps);
                        if (stop) { break; }
                        lastPercent10 = percent10;
                    }

                    if (i1 < N) {
                        break;
                    }

                    arraycopy(XY, 0, B, Bi, Yi);                     // ROMix - 10

                    // for (var i = 0; i < p; i++)...
                    i0++;
                    if (i0 < p) {
                        state = 0;
                        break;
                    }

                    b = [];
                    for (var i = 0; i < B.length; i++) {
                        b.push((B[i] >>  0) & 0xff);
                        b.push((B[i] >>  8) & 0xff);
                        b.push((B[i] >> 16) & 0xff);
                        b.push((B[i] >> 24) & 0xff);
                    }

                    var derivedKey = PBKDF2_HMAC_SHA256_OneIter(password, b, dkLen);

                    // Done; don't break (which would reschedule)
                    return callback(null, 1.0, derivedKey);
                }

                // Schedule the next steps
                nextTick(incrementalSMix);
            }

            // Bootstrap the incremental smix
            incrementalSMix();
    }
9621
def binary_encode_any_high_ascii_in_hash(hash)
      Hash[hash.map { |key, value| [key, binary_encode_any_high_ascii(value)] }]
    end
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
680808
def sign_transaction(self, txins: Union[TxOut],
                         tx: MutableTransaction) -> MutableTransaction:
        ''''''

        solver = P2pkhSolver(self._private_key)
        return tx.spend(txins, [solver for i in txins])
1038724
function generatePskSecret(ecdhForLocalDevice, remotePeerPublicKey,
                                  pskIdentityField) {
  var sxy = ecdhForLocalDevice.computeSecret(remotePeerPublicKey);
  return HKDF(module.exports.SHA256, sxy, pskIdentityField)
    .derive('', module.exports.AES_256_KEY_SIZE);
}
56793
def embed_data_in_blockchain(data, private_key,
        blockchain_client=BlockchainInfoClient(), fee=OP_RETURN_FEE,
        change_address=None, format='bin'):
    
    # build and sign the tx
    signed_tx = make_op_return_tx(data, private_key, blockchain_client,
        fee=fee, change_address=change_address, format=format)
    # dispatch the signed transction to the network
    response = broadcast_transaction(signed_tx, blockchain_client)
    # return the response
    return response