finalize method

  1. @override
Tx finalize()
override

Implementation

@override
Tx finalize() {
  final inputs = <TxInput>[];
  for (var i = 0; i < _inputCount; i++) {
    final section = getInputSection(i);
    Uint8List? txid;
    int vout = 0;
    int sequence = TxInput.sequenceFinal;
    Uint8List? finalScriptSig;

    for (final kv in section) {
      if (kv.key.isEmpty) continue;
      final keyType = kv.key[0];
      if (keyType == PsbtInputEntry.previousTxid.keyType) {
        txid = kv.value;
      } else if (keyType == PsbtInputEntry.outputIndex.keyType &&
          kv.value.length >= 4) {
        vout = kv.value[0] |
            (kv.value[1] << 8) |
            (kv.value[2] << 16) |
            (kv.value[3] << 24);
      } else if (keyType == PsbtInputEntry.sequence.keyType &&
          kv.value.length >= 4) {
        sequence = kv.value[0] |
            (kv.value[1] << 8) |
            (kv.value[2] << 16) |
            (kv.value[3] << 24);
      } else if (keyType == PsbtInputEntry.finalScriptSig.keyType) {
        finalScriptSig = kv.value;
      }
    }

    if (txid == null) {
      throw StateError('Input $i missing previous txid');
    }

    inputs.add(RawInput(
      prevOut: Outpoint(txid: txid, vout: vout),
      scriptSig: finalScriptSig,
      sequence: sequence,
    ));
  }

  final outputs = <TxOutput>[];
  for (var i = 0; i < _outputCount; i++) {
    final section = _getOutputSection(i);
    BigInt? amount;
    Uint8List? script;

    for (final kv in section) {
      if (kv.key.isEmpty) continue;
      final keyType = kv.key[0];
      if (keyType == PsbtOutputEntry.amount.keyType &&
          kv.value.length >= 8) {
        final reader = WireReader(kv.value);
        amount = reader.readUInt64();
      } else if (keyType == PsbtOutputEntry.script.keyType) {
        script = kv.value;
      }
    }

    if (amount == null || script == null) {
      throw StateError('Output $i missing amount or script');
    }

    outputs.add(TxOutput(value: amount, scriptPubKey: script));
  }

  return Tx(
    version: _txVersion,
    inputs: inputs,
    outputs: outputs,
    locktime: _locktime,
  );
}