Skip to content

Commit

Permalink
🐛 Ignores empty subaccount and fixes checksum output
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexV525 committed Sep 29, 2024
1 parent 6017e50 commit 103ea31
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
21 changes: 13 additions & 8 deletions lib/principal/principal.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,16 @@ const _suffixAnonymous = 4;
const _maxLengthInBytes = 29;
const _typeOpaque = 1;

final _emptySubAccount = Uint8List(32);

class Principal {
const Principal(
Principal(
this.principal, {
this.subAccount,
}) : assert(subAccount == null || subAccount.length == 32);
Uint8List? subAccount,
}) : assert(subAccount == null || subAccount.length == 32),
subAccount = subAccount != null && subAccount.eq(_emptySubAccount)
? null
: subAccount;

factory Principal.selfAuthenticating(Uint8List publicKey) {
final sha = sha224Hash(publicKey.buffer);
Expand Down Expand Up @@ -130,7 +135,7 @@ class Principal {
final Uint8List? subAccount;

Principal newSubAccount(Uint8List? subAccount) {
if (subAccount == null) {
if (subAccount == null || subAccount.eq(_emptySubAccount)) {
return this;
}
if (this.subAccount == null || !this.subAccount!.eq(subAccount)) {
Expand Down Expand Up @@ -160,10 +165,6 @@ class Principal {
}
final buffer = StringBuffer(matches.map((e) => e.group(0)).join('-'));
if (subAccount != null) {
final checksum = base32Encode(
_getChecksum(Uint8List.fromList(principal + subAccount!).buffer),
);
buffer.write('-$checksum');
final subAccountHex = subAccount!.toHex();
int nonZeroStart = 0;
while (nonZeroStart < subAccountHex.length) {
Expand All @@ -173,6 +174,10 @@ class Principal {
nonZeroStart++;
}
if (nonZeroStart != subAccountHex.length) {
final checksum = base32Encode(
_getChecksum(Uint8List.fromList(principal + subAccount!).buffer),
);
buffer.write('-$checksum');
buffer.write('.');
buffer.write(subAccountHex.replaceRange(0, nonZeroStart, ''));
}
Expand Down
9 changes: 9 additions & 0 deletions test/principal/principal.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:typed_data';

import 'package:agent_dart/principal/principal.dart';
import 'package:flutter_test/flutter_test.dart';

Expand Down Expand Up @@ -85,6 +87,13 @@ void principalTest() {
'z4s7u-byaaa-aaaao-a3paa-cai-l435n4y'
'.1de15338bedf41b306d4ef5615d1f94fd7b0474b9255690cbe78d2309f02',
);
expect(
Principal(
Uint8List.fromList([0, 0, 0, 0, 0, 224, 17, 26, 1, 1]),
subAccount: Uint8List(32),
).toText(),
'lrllq-iqaaa-aaaah-acena-cai',
);
});

test('errors out on invalid checksums', () {
Expand Down

0 comments on commit 103ea31

Please sign in to comment.