hashForWitnessV0 method

Uint8List hashForWitnessV0(
  1. int inIndex,
  2. Uint8List prevOutScript,
  3. int value,
  4. int hashType,
)

Implementation

Uint8List hashForWitnessV0(
    int inIndex, Uint8List prevOutScript, int value, int hashType) {
  var hashOutputs = ZERO;
  var hashPrevouts = ZERO;
  var hashSequence = ZERO;

  if ((hashType & SIGHASH_ANYONECANPAY) == 0) {
    final prevoutsBuf = Buffer(36 * ins.length);

    for (var txIn in ins) {
      prevoutsBuf.writeSlice(txIn.hash);
      prevoutsBuf.writeUInt32(txIn.index);
    }
    hashPrevouts = prevoutsBuf.toHash256();
  }

  if ((hashType & SIGHASH_ANYONECANPAY) == 0 &&
      (hashType & 0x1f) != SIGHASH_SINGLE &&
      (hashType & 0x1f) != SIGHASH_NONE) {
    final sequenceBuf = Buffer(4 * ins.length);

    for (var txIn in ins) {
      sequenceBuf.writeUInt32(txIn.sequence);
    }
    hashSequence = sequenceBuf.toHash256();
  }

  if ((hashType & 0x1f) != SIGHASH_SINGLE &&
      (hashType & 0x1f) != SIGHASH_NONE) {
    final txOutsSize = outs.fold(
        0,
        (dynamic sum, output) =>
            sum +
            (version! > MIN_VERSION_NO_TOKENS ? 1 : 0) +
            8 +
            varSliceSize(output.script!));
    final outputsBuf = Buffer(txOutsSize);

    for (var txOut in outs) {
      outputsBuf.writeUInt64(txOut.value);
      outputsBuf.writeVarSlice(txOut.script);
      if (version! > MIN_VERSION_NO_TOKENS) outputsBuf.writeVarInt(txOut.tokenId);
    }
    hashOutputs = outputsBuf.toHash256();
  } else if ((hashType & 0x1f) == SIGHASH_SINGLE && inIndex < outs.length) {
    // SIGHASH_SINGLE only hash that according output
    final output = outs[inIndex];
    final outputsBuf = Buffer(8 +
        (version! > MIN_VERSION_NO_TOKENS ? 1 : 0) +
        varSliceSize(output.script!));

    outputsBuf.writeUInt64(output.value);
    outputsBuf.writeVarSlice(output.script);
    if (version! > MIN_VERSION_NO_TOKENS)
      outputsBuf.writeVarInt(output.tokenId);

    hashOutputs = outputsBuf.toHash256();
  }

  final buf = Buffer(156 + varSliceSize(prevOutScript));
  final input = ins[inIndex];
  buf.writeUInt32(version);
  buf.writeSlice(hashPrevouts);
  buf.writeSlice(hashSequence);
  buf.writeSlice(input.hash);
  buf.writeUInt32(input.index);
  buf.writeVarSlice(prevOutScript);
  buf.writeUInt64(value);
  buf.writeUInt32(input.sequence);
  buf.writeSlice(hashOutputs);
  buf.writeUInt32(locktime);
  buf.writeUInt32(hashType);

  return buf.toHash256();
}