isValidWsSubscription function
Validate a WebSocket subscription to a script/address
Returns true if valid, or an error message string if invalid
Implementation
dynamic isValidWsSubscription(WsSubScriptClient subscription) {
final scriptType = subscription.scriptType;
final payload = subscription.payload;
// Test for odd length
if (payload.length % 2 != 0) {
return 'Odd hex length: $payload';
}
// Test for valid hex
if (!_validHexRegex.hasMatch(payload)) {
return 'Invalid hex: "$payload". Payload must be lowercase hex string.';
}
// 20 bytes
const supportedHashBytesP2pkhP2sh = 20;
const supportedHashBytesP2pk = [33, 65];
final payloadBytes = payload.length ~/ 2;
switch (scriptType) {
case 'p2pkh':
case 'p2sh':
// Test for length
if (payloadBytes != supportedHashBytesP2pkhP2sh) {
return 'Invalid length, expected 20 bytes but got $payloadBytes bytes';
}
return true;
case 'p2pk':
if (!supportedHashBytesP2pk.contains(payloadBytes)) {
return 'Invalid length, expected one of [33, 65] but got $payloadBytes bytes';
}
return true;
case 'other':
// Only tests here are for odd length and valid hex, already performed
return true;
default:
// Unsupported type
return 'Invalid scriptType: $scriptType';
}
}