PartialTxV1.fromBytes constructor

PartialTxV1.fromBytes(
  1. Uint8List bytes
)

Implementation

factory PartialTxV1.fromBytes(Uint8List bytes) {
  final sections = PsbtCodec.decode(bytes);
  if (sections.isEmpty) {
    throw FormatException('Invalid PSBT: no global section');
  }

  final global = sections[0];
  // BIP-174: the unsigned tx key must be the 1-byte type, no key data.
  for (final kv in global) {
    _requireNoKeyData(kv.key, _globalKeydataLessTypes);
  }
  Tx? unsignedTx;
  for (final kv in global) {
    if (kv.key.isNotEmpty &&
        kv.key[0] == PsbtGlobal.unsignedTx.keyType) {
      unsignedTx = _parseUnsignedTx(kv.value);
      break;
    }
  }

  // BIP-174 map-count consistency: one global map plus exactly one map
  // per unsigned-transaction input and output.
  if (unsignedTx != null) {
    final inputCount = unsignedTx.inputs.length;
    final outputCount = unsignedTx.outputs.length;
    final expectedMapCount = 1 + inputCount + outputCount;
    if (sections.length != expectedMapCount) {
      throw FormatException(
        'Invalid PSBT v0 map count: expected $expectedMapCount '
        '(1 global + $inputCount input + $outputCount output), got '
        '${sections.length}',
      );
    }
    for (var i = 0; i < inputCount; i++) {
      for (final kv in sections[1 + i]) {
        _requireNoKeyData(kv.key, _inputKeydataLessTypes);
      }
    }
    for (var i = 0; i < outputCount; i++) {
      for (final kv in sections[1 + inputCount + i]) {
        _requireNoKeyData(kv.key, _outputKeydataLessTypes);
      }
    }
  }

  final result = PartialTxV1(unsignedTx: unsignedTx);
  result._sections = sections;
  return result;
}