| 1 | import 'package:bitcoin_base/bitcoin_base.dart'; |
| 2 | import 'package:blockchain_utils/blockchain_utils.dart'; |
| 3 | import 'package:flutter/foundation.dart'; |
| 4 | import 'package:ledger_bitcoin/psbt.dart'; |
| 5 | import 'package:ledger_bitcoin/src/psbt/map_extension.dart'; |
| 6 | import 'package:ledger_bitcoin/src/utils/buffer_reader.dart'; |
| 7 | import 'package:ledger_bitcoin/src/utils/uint8list_extension.dart' as ext; |
| 8 | |
| 9 | extension PsbtSigner on PsbtV2 { |
| 10 | void deserializeV0(Uint8List psbt) { |
| 11 | final bufferReader = BufferReader(psbt); |
| 12 | if (!listEquals( |
| 13 | bufferReader.readSlice(5), Uint8List.fromList([0x70, 0x73, 0x62, 0x74, 0xff]))) { |
| 14 | throw Exception("Invalid magic bytes"); |
| 15 | } |
| 16 | while (_readKeyPair(globalMap, bufferReader)) {} |
| 17 | |
| 18 | final tx = BtcTransaction.fromRaw(BytesUtils.toHexString(globalMap['00']!)); |
| 19 | |
| 20 | setGlobalInputCount(tx.inputs.length); |
| 21 | setGlobalOutputCount(tx.outputs.length); |
| 22 | setGlobalTxVersion(Uint8List.fromList(tx.version).readUint32LE(0)); |
| 23 | |
| 24 | for (var i = 0; i < getGlobalInputCount(); i++) { |
| 25 | inputMaps.insert(i, <String, Uint8List>{}); |
| 26 | while (_readKeyPair(inputMaps[i], bufferReader)) {} |
| 27 | final input = tx.inputs[i]; |
| 28 | setInputOutputIndex(i, input.txIndex); |
| 29 | setInputPreviousTxId( |
| 30 | i, Uint8List.fromList(BytesUtils.fromHexString(input.txId).reversed.toList())); |
| 31 | setInputSequence(i, Uint8List.fromList(input.sequence).readUint32LE(0)); |
| 32 | } |
| 33 | for (var i = 0; i < getGlobalOutputCount(); i++) { |
| 34 | outputMaps.insert(i, <String, Uint8List>{}); |
| 35 | while (_readKeyPair(outputMaps[i], bufferReader)) {} |
| 36 | final output = tx.outputs[i]; |
| 37 | setOutputAmount(i, output.amount.toInt()); |
| 38 | setOutputScript(i, Uint8List.fromList(output.scriptPubKey.toBytes())); |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | bool _readKeyPair(Map<String, Uint8List> map, BufferReader bufferReader) { |
| 43 | final keyLen = bufferReader.readVarInt(); |
| 44 | if (keyLen == 0) return false; |
| 45 | |
| 46 | final keyType = bufferReader.readUInt8(); |
| 47 | final keyData = bufferReader.readSlice(keyLen - 1); |
| 48 | final value = bufferReader.readVarSlice(); |
| 49 | |
| 50 | map.set(keyType, keyData, value); |
| 51 | return true; |
| 52 | } |
| 53 | } |