From 103ea31f50d337cc8619e54471eab5670a137d2d Mon Sep 17 00:00:00 2001 From: Alex Li Date: Sun, 29 Sep 2024 10:30:02 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20Ignores=20empty=20subaccount=20a?= =?UTF-8?q?nd=20fixes=20checksum=20output?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/principal/principal.dart | 21 +++++++++++++-------- test/principal/principal.dart | 9 +++++++++ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/lib/principal/principal.dart b/lib/principal/principal.dart index 333bbdd1..a94971e7 100644 --- a/lib/principal/principal.dart +++ b/lib/principal/principal.dart @@ -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); @@ -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)) { @@ -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) { @@ -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, '')); } diff --git a/test/principal/principal.dart b/test/principal/principal.dart index 97e6f62d..e45a06d2 100644 --- a/test/principal/principal.dart +++ b/test/principal/principal.dart @@ -1,3 +1,5 @@ +import 'dart:typed_data'; + import 'package:agent_dart/principal/principal.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -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', () {