scriptPubKeyFromAddress static method
Converts a Bitcoin mainnet address into its standard output script.
BTCB2 signs P2PKH inputs in the first version, but accepts P2PKH, P2SH, SegWit v0 and Taproot destination outputs.
Implementation
static List<int> scriptPubKeyFromAddress(String address) {
try {
final decoded = blockchain.Base58Decoder.checkDecode(address);
if (decoded.length == 21 && decoded.first == 0x00) {
return [0x76, 0xa9, 0x14, ...decoded.sublist(1), 0x88, 0xac];
}
if (decoded.length == 21 && decoded.first == 0x05) {
return [0xa9, 0x14, ...decoded.sublist(1), 0x87];
}
} catch (_) {
// It may be a SegWit address; try Bech32/Bech32m below.
}
try {
final decoded = blockchain.SegwitBech32Decoder.decode('bc', address);
final version = decoded.$1;
final program = decoded.$2;
if (version < 0 ||
version > 16 ||
program.length < 2 ||
program.length > 40) {
throw const FormatException('Invalid SegWit witness program.');
}
if (version == 0 && program.length != 20 && program.length != 32) {
throw const FormatException('Invalid SegWit v0 witness program.');
}
final versionOpcode = version == 0 ? 0x00 : 0x50 + version;
return [versionOpcode, program.length, ...program];
} catch (_) {
throw FormatException('Unsupported Bitcoin mainnet address: $address');
}
}