A witness program is any valid Script that consists of a 1-byte push opcode followed by a data push between 2 and 40 bytes.
492707
def witness_program?
      return false if size < 4 || size > 42 || chunks.size < 2

      opcode = chunks[0].opcode

      return false if opcode != OP_0 && (opcode < OP_1 || opcode > OP_16)
      return false unless chunks[1].pushdata?

      if size == (chunks[1][0].unpack('C').first + 2)
        program_size = chunks[1].pushed_data.bytesize
        return program_size >= 2 && program_size <= 40
      end

      false
    end
677803
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
        String keyBytes = Base64Utils.encode(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes.getBytes());
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicK = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(publicK);
        signature.update(data);
        return signature.verify(Base64Utils.decode(sign).getBytes());
    }
744544
def make_sh_output_script(script_string, witness=False):
    '''
    
    '''
    if witness and not riemann.network.SEGWIT:
        raise ValueError(
            'Network {} does not support witness scripts.'
            .format(riemann.get_current_network_name()))

    script_bytes = serialization.serialize(script_string)
    return make_sh_script_pubkey(script_bytes=script_bytes, witness=witness)
861710
def p2sh_input_and_witness(outpoint, stack_script,
                           redeem_script, sequence=None):
    '''
    
    '''
    if sequence is None:
        sequence = guess_sequence(redeem_script)

    stack_script = script_ser.serialize(stack_script)
    redeem_script = script_ser.hex_serialize(redeem_script)
    redeem_script = script_ser.serialize(redeem_script)

    return tb.make_legacy_input_and_empty_witness(
        outpoint=outpoint,
        stack_script=stack_script,
        redeem_script=redeem_script,
        sequence=sequence)
1227958
def append_opcode(opcode)
      raise ArgumentError, "Invalid opcode value." if opcode > 0xff || opcode < 0
      if opcode > 0 && opcode <= OP_PUSHDATA4
        raise ArgumentError, "Cannot add pushdata opcode without data"
      end
      @chunks << ScriptChunk.new(opcode.chr)
      return self
    end
485047
def serialize_witness_format
      buf = [version, MARKER, FLAG].pack('Vcc')
      buf << Bitcoin.pack_var_int(inputs.length) << inputs.map(&:to_payload).join
      buf << Bitcoin.pack_var_int(outputs.length) << outputs.map(&:to_payload).join
      buf << witness_payload << [lock_time].pack('V')
      buf
    end
72504
def btc_tx_serialize(_txobj):
    
    
    # output buffer
    o = []
    txobj = None
    if encoding.json_is_base(_txobj, 16):
        # txobj is built from hex strings already.  deserialize them 
        txobj = encoding.json_changebase(_txobj, lambda x: binascii.unhexlify(x))
    else:
        txobj = copy.deepcopy(_txobj)

    # version
    o.append(encoding.encode(txobj["version"], 256, 4)[::-1])

    # do we have any witness scripts?
    have_witness = False
    for inp in txobj['ins']:
        if inp.has_key('witness_script') and len(inp['witness_script']) > 0:
            have_witness = True
            break

    if have_witness:
        # add segwit marker 
        o.append('\x00\x01')
    
    # number of inputs
    o.append(encoding.num_to_var_int(len(txobj["ins"])))

    # all inputs
    for inp in txobj["ins"]:
        # input tx hash
        o.append(inp["outpoint"]["hash"][::-1])

        # input tx outpoint
        o.append(encoding.encode(inp["outpoint"]["index"], 256, 4)[::-1])

        # input scriptsig
        script = inp.get('script')
        if not script:
            script = bytes()

        scriptsig = encoding.num_to_var_int(len(script)) + script
        o.append(scriptsig)

        # sequence
        o.append(encoding.encode(inp.get("sequence", UINT_MAX - 1), 256, 4)[::-1])

    # number of outputs
    o.append(encoding.num_to_var_int(len(txobj["outs"])))

    # all outputs
    for out in txobj["outs"]:
        # value
        o.append(encoding.encode(out["value"], 256, 8)[::-1])

        # scriptPubKey
        scriptpubkey = encoding.num_to_var_int(len(out['script'])) + out['script']
        o.append(scriptpubkey)

    # add witnesses 
    if have_witness:
        for inp in txobj['ins']:
            witness_script = inp.get('witness_script')
            if not witness_script:
                witness_script = '\x00'

            o.append(witness_script)

    # locktime
    o.append(encoding.encode(txobj["locktime"], 256, 4)[::-1])

    # full string
    ret = ''.join( encoding.json_changebase(o, lambda x: encoding.safe_hexlify(x)) )
    return ret
210989
def program_checks(job, input_args):
    
    # Program checks
    for program in ['curl', 'docker', 'unzip', 'samtools']:
        assert which(program), 'Program "{}" must be installed on every node.'.format(program)
    job.addChildJobFn(download_shared_files, input_args)
702294
def make_sh_output(value, output_script, witness=False):
    '''
    
    '''
    return _make_output(
        value=utils.i2le_padded(value, 8),
        output_script=make_sh_output_script(output_script, witness))
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)
73632
def check_minimal_push(data, opcode)
      if data.bytesize == 0
        # Could have used OP_0.
        return opcode == OP_0
      elsif data.bytesize == 1 && data.bytes[0] >= 1 && data.bytes[0] <= 16
        # Could have used OP_1 .. OP_16.
        return opcode == OP_1 + (data.bytes[0] - 1)
      elsif data.bytesize == 1 && data.bytes[0] == 0x81
        # Could have used OP_1NEGATE.
        return opcode == OP_1NEGATE
      elsif data.bytesize <= 75
        # Could have used a direct push (opcode indicating number of bytes pushed + those bytes).
        return opcode == data.bytesize
      elsif data.bytesize <= 255
        # Could have used OP_PUSHDATA.
        return opcode == OP_PUSHDATA1
      elsif (data.bytesize <= 65535)
        # Could have used OP_PUSHDATA2.
        return opcode == OP_PUSHDATA2
      end
      return true
    end
1254438
public static boolean isWitnessCommitment(Script script) {
        List<ScriptChunk> chunks = script.chunks;
        if (chunks.size() < 2)
            return false;
        if (!chunks.get(0).equalsOpCode(ScriptOpCodes.OP_RETURN))
            return false;
        byte[] chunkData = chunks.get(1).data;
        if (chunkData == null || chunkData.length != 36)
            return false;
        if (!Arrays.equals(Arrays.copyOfRange(chunkData, 0, 4), SEGWIT_COMMITMENT_HEADER))
            return false;
        return true;
    }
130803
function decompressScript(script, br) {
  // Decompress the script.
  switch (br.readU8()) {
    case 0: {
      const hash = br.readBytes(20, true);
      script.fromPubkeyhash(hash);
      break;
    }
    case 1: {
      const hash = br.readBytes(20, true);
      script.fromScripthash(hash);
      break;
    }
    case 2:
    case 3:
    case 4:
    case 5: {
      br.offset -= 1;
      const data = br.readBytes(33, true);
      // Decompress the key. If this fails,
      // we have database corruption!
      const key = decompressKey(data);
      script.fromPubkey(key);
      break;
    }
    default: {
      br.offset -= 1;
      const size = br.readVarint() - COMPRESS_TYPES;
      if (size > consensus.MAX_SCRIPT_SIZE) {
        // This violates consensus rules.
        // We don't need to read it.
        script.fromNulldata(EMPTY_BUFFER);
        br.seek(size);
      } else {
        const data = br.readBytes(size);
        script.fromRaw(data);
      }
      break;
    }
  }

  return script;
}
397717
function SignResultPacket(total, witness, script) {
  Packet.call(this);
  this.total = total || 0;
  this.script = script || [];
  this.witness = witness || [];
}
1258446
public static Script createP2SHMultiSigInputScript(@Nullable List<TransactionSignature> signatures,
                                                       Script multisigProgram) {
        List<byte[]> sigs = new ArrayList<>();
        if (signatures == null) {
            // create correct number of empty signatures
            int numSigs = multisigProgram.getNumberOfSignaturesRequiredToSpend();
            for (int i = 0; i < numSigs; i++)
                sigs.add(new byte[]{});
        } else {
            for (TransactionSignature signature : signatures) {
                sigs.add(signature.encodeToBitcoin());
            }
        }
        return createMultiSigInputScriptBytes(sigs, multisigProgram.getProgram());
    }

    /**
     * Create a program that satisfies an OP_CHECKMULTISIG program, using pre-encoded signatures. 
     * Optionally, appends the script program bytes if spending a P2SH output.
     */
    public static Script createMultiSigInputScriptBytes(List<byte[]> signatures, @Nullable byte[] multisigProgramBytes) {
        checkArgument(signatures.size() <= 16);
        ScriptBuilder builder = new ScriptBuilder();
        builder.smallNum(0);  // Work around a bug in CHECKMULTISIG that is now a required part of the protocol.
        for (byte[] signature : signatures)
            builder.data(signature);
        if (multisigProgramBytes!= null)
            builder.data(multisigProgramBytes);
        return builder.build();
    }

    /**
     * Returns a copy of the given scriptSig with the signature inserted in the given position.
     *
     * This function assumes that any missing sigs have OP_0 placeholders. If given scriptSig already has all the signatures
     * in place, IllegalArgumentException will be thrown.
     *
     * @param targetIndex where to insert the signature
     * @param sigsPrefixCount how many items to copy verbatim (e.g. initial OP_0 for multisig)
     * @param sigsSuffixCount how many items to copy verbatim at end (e.g. redeemScript for P2SH)
     */
    public static Script updateScriptWithSignature(Script scriptSig, byte[] signature, int targetIndex,
                                                   int sigsPrefixCount, int sigsSuffixCount) {
        ScriptBuilder builder = new ScriptBuilder();
        List<ScriptChunk> inputChunks = scriptSig.getChunks();
        int totalChunks = inputChunks.size();

        // Check if we have a place to insert, otherwise just return given scriptSig unchanged.
        // We assume here that OP_0 placeholders always go after the sigs, so
        // to find if we have sigs missing, we can just check the chunk in latest sig position
        boolean hasMissingSigs = inputChunks.get(totalChunks - sigsSuffixCount - 1).equalsOpCode(OP_0);
        checkArgument(hasMissingSigs, "ScriptSig is already filled with signatures");

        // copy the prefix
        for (ScriptChunk chunk: inputChunks.subList(0, sigsPrefixCount))
            builder.addChunk(chunk);

        // copy the sigs
        int pos = 0;
        boolean inserted = false;
        for (ScriptChunk chunk: inputChunks.subList(sigsPrefixCount, totalChunks - sigsSuffixCount)) {
            if (pos == targetIndex) {
                inserted = true;
                builder.data(signature);
                pos++;
            }
            if (!chunk.equalsOpCode(OP_0)) {
                builder.addChunk(chunk);
                pos++;
            }
        }

        // add OP_0's if needed, since we skipped them in the previous loop
        while (pos < totalChunks - sigsPrefixCount - sigsSuffixCount) {
            if (pos == targetIndex) {
                inserted = true;
                builder.data(signature);
            }
            else {
                builder.addChunk(new ScriptChunk(OP_0, null));
            }
            pos++;
        }

        // copy the suffix
        for (ScriptChunk chunk: inputChunks.subList(totalChunks - sigsSuffixCount, totalChunks))
            builder.addChunk(chunk);

        checkState(inserted);
        return builder.build();
    }

    /** Creates a scriptPubKey that encodes payment to the given raw public key. */
    public static Script createP2PKOutputScript(byte[] pubKey) {
        return new ScriptBuilder().data(pubKey).op(OP_CHECKSIG).build();
    }

    /** Creates a scriptPubKey that encodes payment to the given raw public key. */
    public static Script createP2PKOutputScript(ECKey pubKey) {
        return createP2PKOutputScript(pubKey.getPubKey());
    }

    /**
     * Creates a scriptPubKey that sends to the given public key hash.
     */
    public static Script createP2PKHOutputScript(byte[] hash) {
        checkArgument(hash.length == LegacyAddress.LENGTH);
        ScriptBuilder builder = new ScriptBuilder();
        builder.op(OP_DUP);
        builder.op(OP_HASH160);
        builder.data(hash);
        builder.op(OP_EQUALVERIFY);
        builder.op(OP_CHECKSIG);
        return builder.build();
    }

    /**
     * Creates a scriptPubKey that sends to the given public key.
     */
    public static Script createP2PKHOutputScript(ECKey key) {
        checkArgument(key.isCompressed());
        return createP2PKHOutputScript(key.getPubKeyHash());
    }

    /**
     * Creates a segwit scriptPubKey that sends to the given public key hash.
     */
    public static Script createP2WPKHOutputScript(byte[] hash) {
        checkArgument(hash.length == SegwitAddress.WITNESS_PROGRAM_LENGTH_PKH);
        return new ScriptBuilder().smallNum(0).data(hash).build();
    }

    /**
     * Creates a segwit scriptPubKey that sends to the given public key.
     */
    public static Script createP2WPKHOutputScript(ECKey key) {
        checkArgument(key.isCompressed());
        return createP2WPKHOutputScript(key.getPubKeyHash());
    }

    /**
     * Creates a scriptPubKey that sends to the given script hash. Read
     * <a href="https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki">BIP 16</a> to learn more about this
     * kind of script.
     */
    public static Script createP2SHOutputScript(byte[] hash) {
        checkArgument(hash.length == 20);
        return new ScriptBuilder().op(OP_HASH160).data(hash).op(OP_EQUAL).build();
    }

    /**
     * Creates a scriptPubKey for the given redeem script.
     */
    public static Script createP2SHOutputScript(Script redeemScript) {
        byte[] hash = Utils.sha256hash160(redeemScript.getProgram());
        return ScriptBuilder.createP2SHOutputScript(hash);
    }

    /**
     * Creates a segwit scriptPubKey that sends to the given script hash.
     */
    public static Script createP2WSHOutputScript(byte[] hash) {
        checkArgument(hash.length == SegwitAddress.WITNESS_PROGRAM_LENGTH_SH);
        return new ScriptBuilder().smallNum(0).data(hash).build();
    }

    /**
     * Creates a segwit scriptPubKey for the given redeem script.
     */
    public static Script createP2WSHOutputScript(Script redeemScript) {
        byte[] hash = Sha256Hash.hash(redeemScript.getProgram());
        return ScriptBuilder.createP2WSHOutputScript(hash);
    }

    /**
     * Creates a P2SH output script with given public keys and threshold. Given public keys will be placed in
     * redeem script in the lexicographical sorting order.
     */
    public static Script createP2SHOutputScript(int threshold, List<ECKey> pubkeys) {
        Script redeemScript = createRedeemScript(threshold, pubkeys);
        return createP2SHOutputScript(redeemScript);
    }

    /**
     * Creates redeem script with given public keys and threshold. Given public keys will be placed in
     * redeem script in the lexicographical sorting order.
     */
    public static Script createRedeemScript(int threshold, List<ECKey> pubkeys) {
        pubkeys = new ArrayList<>(pubkeys);
        Collections.sort(pubkeys, ECKey.PUBKEY_COMPARATOR);
        return ScriptBuilder.createMultiSigOutputScript(threshold, pubkeys);
    }

    /**
     * Creates a script of the form OP_RETURN [data]. This feature allows you to attach a small piece of data (like
     * a hash of something stored elsewhere) to a zero valued output which can never be spent and thus does not pollute
     * the ledger.
     */
    public static Script createOpReturnScript(byte[] data) {
        checkArgument(data.length <= 80);
        return new ScriptBuilder().op(OP_RETURN).data(data).build();
    }

    public static Script createCLTVPaymentChannelOutput(BigInteger time, ECKey from, ECKey to) {
        byte[] timeBytes = Utils.reverseBytes(Utils.encodeMPI(time, false));
        if (timeBytes.length > 5) {
            throw new RuntimeException("Time too large to encode as 5-byte int");
        }
        return new ScriptBuilder().op(OP_IF)
                .data(to.getPubKey()).op(OP_CHECKSIGVERIFY)
                .op(OP_ELSE)
                .data(timeBytes).op(OP_CHECKLOCKTIMEVERIFY).op(OP_DROP)
                .op(OP_ENDIF)
                .data(from.getPubKey()).op(OP_CHECKSIG).build();
    }

    public static Script createCLTVPaymentChannelRefund(TransactionSignature signature) {
        ScriptBuilder builder = new ScriptBuilder();
        builder.data(signature.encodeToBitcoin());
        builder.data(new byte[] { 0 }); // Use the CHECKLOCKTIMEVERIFY if branch
        return builder.build();
    }

    public static Script createCLTVPaymentChannelP2SHRefund(TransactionSignature signature, Script redeemScript) {
        ScriptBuilder builder = new ScriptBuilder();
        builder.data(signature.encodeToBitcoin());
        builder.data(new byte[] { 0 }); // Use the CHECKLOCKTIMEVERIFY if branch
        builder.data(redeemScript.getProgram());
        return builder.build();
    }

    public static Script createCLTVPaymentChannelP2SHInput(byte[] from, byte[] to, Script redeemScript) {
        ScriptBuilder builder = new ScriptBuilder();
        builder.data(from);
        builder.data(to);
        builder.smallNum(1); // Use the CHECKLOCKTIMEVERIFY if branch
        builder.data(redeemScript.getProgram());
        return builder.build();
    }

    public static Script createCLTVPaymentChannelInput(TransactionSignature from, TransactionSignature to) {
        return createCLTVPaymentChannelInput(from.encodeToBitcoin(), to.encodeToBitcoin());
    }

    public static Script createCLTVPaymentChannelInput(byte[] from, byte[] to) {
        ScriptBuilder builder = new ScriptBuilder();
        builder.data(from);
        builder.data(to);
        builder.smallNum(1); // Use the CHECKLOCKTIMEVERIFY if branch
        return builder.build();
    }
}
938652
private static void executeCheckLockTimeVerify(Transaction txContainingThis, int index, LinkedList<byte[]> stack, Set<VerifyFlag> verifyFlags) throws ScriptException {
        if (stack.size() < 1)
            throw new ScriptException(ScriptError.SCRIPT_ERR_INVALID_STACK_OPERATION, "Attempted OP_CHECKLOCKTIMEVERIFY on a stack with size < 1");

        // Thus as a special case we tell CScriptNum to accept up
        // to 5-byte bignums to avoid year 2038 issue.
        final BigInteger nLockTime = castToBigInteger(stack.getLast(), 5, verifyFlags.contains(VerifyFlag.MINIMALDATA));

        if (nLockTime.compareTo(BigInteger.ZERO) < 0)
            throw new ScriptException(ScriptError.SCRIPT_ERR_NEGATIVE_LOCKTIME, "Negative locktime");

        // There are two kinds of nLockTime, need to ensure we're comparing apples-to-apples
        if (!(
            ((txContainingThis.getLockTime() <  Transaction.LOCKTIME_THRESHOLD) && (nLockTime.compareTo(Transaction.LOCKTIME_THRESHOLD_BIG)) < 0) ||
            ((txContainingThis.getLockTime() >= Transaction.LOCKTIME_THRESHOLD) && (nLockTime.compareTo(Transaction.LOCKTIME_THRESHOLD_BIG)) >= 0))
        )
            throw new ScriptException(ScriptError.SCRIPT_ERR_UNSATISFIED_LOCKTIME, "Locktime requirement type mismatch");

        // Now that we know we're comparing apples-to-apples, the
        // comparison is a simple numeric one.
        if (nLockTime.compareTo(BigInteger.valueOf(txContainingThis.getLockTime())) > 0)
            throw new ScriptException(ScriptError.SCRIPT_ERR_UNSATISFIED_LOCKTIME, "Locktime requirement not satisfied");

        // Finally the nLockTime feature can be disabled and thus
        // CHECKLOCKTIMEVERIFY bypassed if every txin has been
        // finalized by setting nSequence to maxint. The
        // transaction would be allowed into the blockchain, making
        // the opcode ineffective.
        //
        // Testing if this vin is not final is sufficient to
        // prevent this condition. Alternatively we could test all
        // inputs, but testing just this input minimizes the data
        // required to prove correct CHECKLOCKTIMEVERIFY execution.
        if (!txContainingThis.getInput(index).hasSequence())
            throw new ScriptException(ScriptError.SCRIPT_ERR_UNSATISFIED_LOCKTIME, "Transaction contains a final transaction input for a CHECKLOCKTIMEVERIFY script.");
    }
1262299
def _ser_script_to_sh_address(script_bytes, witness=False, cashaddr=True):
    '''
    
    '''
    if witness:
        script_hash = utils.sha256(script_bytes)
    else:
        script_hash = utils.hash160(script_bytes)
    return _hash_to_sh_address(
        script_hash=script_hash,
        witness=witness,
        cashaddr=cashaddr)