11import 'package:bb_mobile/features/labels/primitive/label_type.dart' ;
2+ import 'package:bs58check/bs58check.dart' as base58;
3+ import 'package:convert/convert.dart' ;
24
35class LabelEntity {
46 final int ? id;
@@ -16,18 +18,80 @@ class LabelEntity {
1618 this .origin,
1719 this .spendable,
1820 }) {
21+ _validateReference ();
22+ }
23+
24+ void _validateReference () {
1925 switch (type) {
2026 case LabelType .transaction:
21- if (reference.length != 64 ) throw Exception ( 'Invalid tx reference' );
27+ _validateTxid (reference);
2228 case LabelType .address:
23- // deserialize using bdk and lwk
29+ // Address validation requires async BDK/LWK calls
30+ break ;
2431 case LabelType .publicKey:
2532 case LabelType .input:
26- // check txid:int
33+ final parts = reference.split (':' );
34+ _validateTxid (parts[0 ]);
35+ _validateIndex (parts[1 ]);
36+
2737 case LabelType .output:
28- // check txid:int
38+ final parts = reference.split (':' );
39+ _validateTxid (parts[0 ]);
40+ _validateIndex (parts[1 ]);
2941 case LabelType .extendedPublicKey:
30- // base58 decode size == 78
42+ _validateExtendedPublicKeyReference ();
43+ }
44+ }
45+
46+ void _validateTxid (String input) {
47+ if (reference.length != 64 ) {
48+ throw LabelValidationException (
49+ 'Invalid transaction reference: must be 64 hex characters' ,
50+ );
51+ }
52+
53+ try {
54+ hex.decode (reference);
55+ } catch (e) {
56+ throw LabelValidationException (
57+ 'Invalid transaction reference: must be valid hex' ,
58+ );
59+ }
60+ }
61+
62+ void _validateIndex (String input) {
63+ final index = int .tryParse (input);
64+ if (index == null || index < 0 ) {
65+ throw LabelValidationException (
66+ 'Invalid index reference: must be a non-negative integer' ,
67+ );
68+ }
69+ }
70+
71+ /// Validates extended public key reference by decoding base58 and checking length
72+ /// Extended keys (xpub, ypub, zpub, tpub, etc.) are 78 bytes when decoded
73+ void _validateExtendedPublicKeyReference () {
74+ try {
75+ final decoded = base58.decode (reference);
76+ if (decoded.length != 78 ) {
77+ throw LabelValidationException (
78+ 'Invalid extended public key reference: decoded length must be 78 bytes, got ${decoded .length }' ,
79+ );
80+ }
81+ } catch (e) {
82+ if (e is LabelValidationException ) rethrow ;
83+ throw LabelValidationException (
84+ 'Invalid extended public key reference: failed to decode base58 - $e ' ,
85+ );
3186 }
3287 }
3388}
89+
90+ class LabelValidationException implements Exception {
91+ final String message;
92+
93+ LabelValidationException (this .message);
94+
95+ @override
96+ String toString () => 'LabelValidationException: $message ' ;
97+ }
0 commit comments