Skip to content

Commit 6375ccb

Browse files
authored
Merge pull request #444 from 0xPolygonID/refactor/drop_native_poseidon
Added env and auth claim retrieval cache.
2 parents c9198bb + 8857c86 commit 6375ccb

File tree

21 files changed

+251
-621
lines changed

21 files changed

+251
-621
lines changed

ios/Classes/SwiftPolygonIdSdkPlugin.swift

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,16 +15,9 @@ public class SwiftPolygonIdSdkPlugin: NSObject, FlutterPlugin {
1515

1616
public static func dummyMethodToEnforceBundling() {
1717
// LibBabyjubjub bindings
18-
pack_signature("16727755406458403965916091816756284515992637653800319054951151706132152331811672775540645840396591609181675628451599263765380031");
19-
unpack_signature("16727755406458403965916091816756284515992637653800319054951151706132152331811672775540645840396591609181675628451599263765380031");
2018
pack_point("17777552123799933955779906779655732241715742912184938656739573121738514868268", "2626589144620713026669568689430873010625803728049924121243784502389097019475");
2119
unpack_point("53b81ed5bffe9545b54016234682e7b2f699bd42a5e9eae27ff4051bc698ce85");
2220
prv2pub("0001020304050607080900010203040506070809000102030405060708090001");
23-
poseidon_hash("");
24-
poseidon_hash2("", "");
25-
poseidon_hash3("", "", "");
26-
poseidon_hash4("", "", "", "");
27-
hash_poseidon("", "", "");
2821
sign_poseidon("", "");
2922
verify_poseidon("", "", "");
3023
let str = "string"

ios/Classes/libbabyjubjub.h

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,11 @@
11
// NOTE: Append the lines below to ios/Classes/<your>Plugin.h
22

3-
char *pack_signature(const char *signature);
4-
5-
char *unpack_signature(const char *compressed_signature);
6-
73
char *pack_point(const char *point_x, const char *point_y);
84

95
char *unpack_point(const char *compressed_point);
106

117
char *prv2pub(const char *private_key);
128

13-
char *poseidon_hash(const char *input);
14-
15-
char *poseidon_hash2(const char *in1, const char *in2);
16-
17-
char *poseidon_hash3(const char *in1, const char *in2, const char *in3);
18-
19-
char *poseidon_hash4(const char *in1, const char *in2, const char *in3, const char *in4);
20-
21-
char *hash_poseidon(const char *claims_tree,
22-
const char *revocation_tree,
23-
const char *roots_tree_root);
24-
259
char *sign_poseidon(const char *private_key, const char *msg);
2610

2711
char *verify_poseidon(const char *private_key,

lib/common/data/repositories/config_repository_impl.dart

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,25 @@
1+
import 'package:injectable/injectable.dart';
12
import 'package:polygonid_flutter_sdk/common/data/data_sources/storage_key_value_data_source.dart';
23
import 'package:polygonid_flutter_sdk/common/data/exceptions/env_exceptions.dart';
34
import 'package:polygonid_flutter_sdk/common/domain/entities/env_entity.dart';
45
import 'package:polygonid_flutter_sdk/common/domain/repositories/config_repository.dart';
56

7+
@singleton
68
class ConfigRepositoryImpl implements ConfigRepository {
79
final StorageKeyValueDataSource _storageKeyValueDataSource;
810

911
ConfigRepositoryImpl(
1012
this._storageKeyValueDataSource,
1113
);
1214

15+
EnvEntity? _envCache;
16+
1317
@override
1418
Future<EnvEntity> getEnv() {
19+
if (_envCache != null) {
20+
return Future.value(_envCache!);
21+
}
22+
1523
return _storageKeyValueDataSource.get(key: "env").then((value) {
1624
if (value == null) {
1725
return Future.error(EnvNotSetException());
@@ -23,18 +31,26 @@ class ConfigRepositoryImpl implements ConfigRepository {
2331

2432
@override
2533
Future<void> setEnv({required EnvEntity env}) {
34+
_envCache = env;
2635
return _storageKeyValueDataSource.store(key: "env", value: env.toJson());
2736
}
2837

38+
String? _selectedChainIdCache;
39+
2940
@override
3041
Future<String?> getSelectedChainId() {
42+
if (_selectedChainIdCache != null) {
43+
return Future.value(_selectedChainIdCache);
44+
}
45+
3146
return _storageKeyValueDataSource.get(key: "selected_chain").then((value) {
3247
return value;
3348
});
3449
}
3550

3651
@override
3752
Future<void> setSelectedChainId({required String chainId}) {
53+
_selectedChainIdCache = chainId;
3854
return _storageKeyValueDataSource.store(
3955
key: "selected_chain", value: chainId);
4056
}

lib/common/domain/use_cases/get_env_use_case.dart

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ class GetEnvUseCase extends FutureUseCase<void, EnvEntity> {
1616
@override
1717
Future<EnvEntity> execute({dynamic param}) {
1818
return _configRepository.getEnv().then((env) {
19-
logger().i("[GetEnvUseCase] Current env is: $env");
19+
logger().d("[GetEnvUseCase] Current env is: $env");
2020

2121
return env;
2222
}).catchError((error) {

lib/common/utils/hex_utils.dart

Lines changed: 0 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -66,87 +66,4 @@ class HexUtils {
6666

6767
return 'hez:${base64Url.encode(finalBuffBjj.toBytes())}';
6868
}
69-
70-
static Uint8List hexToBuffer(String source) {
71-
// String (Dart uses UTF-16) to bytes
72-
List<int> list = [];
73-
for (var rune in source.runes) {
74-
if (rune >= 0x10000) {
75-
rune -= 0x10000;
76-
int firstWord = (rune >> 10) + 0xD800;
77-
list.add(firstWord >> 8);
78-
list.add(firstWord & 0xFF);
79-
int secondWord = (rune & 0x3FF) + 0xDC00;
80-
list.add(secondWord >> 8);
81-
list.add(secondWord & 0xFF);
82-
} else {
83-
list.add(rune >> 8);
84-
list.add(rune & 0xFF);
85-
}
86-
}
87-
Uint8List bytes = Uint8List.fromList(list);
88-
return bytes;
89-
}
90-
91-
/// Converts a buffer to a hexadecimal representation
92-
///
93-
/// @param {Uint8List} buf
94-
///
95-
/// @returns {String}
96-
static String bufToHex(Uint8List buf) {
97-
return const Utf8Decoder().convert(buf);
98-
}
99-
100-
/// Poseidon hash of a generic buffer
101-
/// @param {Uint8List} msgBuff
102-
/// @returns {BigInt} - final hash
103-
static BigInt hashBuffer(Uint8List msgBuff) {
104-
const n = 31;
105-
List<BigInt> msgArray = [];
106-
final fullParts = (msgBuff.length / n).floor();
107-
for (int i = 0; i < fullParts; i++) {
108-
final v = msgBuff.sublist(n * i, n * (i + 1));
109-
msgArray.add(Uint8ArrayUtils.bytesToBigInt(v));
110-
}
111-
if (msgBuff.length % n != 0) {
112-
final v = msgBuff.sublist(fullParts * n);
113-
msgArray.add(Uint8ArrayUtils.bytesToBigInt(v));
114-
}
115-
return multiHash(msgArray);
116-
}
117-
118-
/// Chunks inputs in five elements and hash with Poseidon all them togheter
119-
/// @param {Array} arr - inputs hash
120-
/// @returns {BigInt} - final hash
121-
static BigInt multiHash(List<BigInt> arr) {
122-
BigInt r = BigInt.zero;
123-
for (int i = 0; i < arr.length; i += 5) {
124-
final fiveElems = [];
125-
for (int j = 0; j < 5; j++) {
126-
if (i + j < arr.length) {
127-
fiveElems.add(arr[i + j]);
128-
} else {
129-
fiveElems.add(BigInt.zero);
130-
}
131-
}
132-
//Pointer<Uint8> ptr =
133-
// Uint8ArrayUtils.toPointer(Uint8List.fromList(fiveElems as List<int>));
134-
//final ph = eddsaBabyJub.hashPoseidon(ptr);
135-
//r = F.add(r, ph);
136-
}
137-
// TODO: fix this
138-
return BigInt.zero;
139-
//return F.normalize(r);
140-
}
141-
142-
/// Mask and shift a BigInt
143-
///
144-
/// @param {BigInt} num - Input number
145-
/// @param {int} origin - Initial bit
146-
/// @param {int} len - Bit length of the mask
147-
/// @returns {BigInt} Scalar
148-
static BigInt extract(BigInt num, int origin, int len) {
149-
BigInt mask = (BigInt.one << len) - BigInt.one;
150-
return (num >> origin) & mask;
151-
}
15269
}

lib/credential/data/data_sources/local_claim_data_source.dart

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
import 'dart:convert';
22

3+
import 'package:injectable/injectable.dart';
4+
35
import '../../../constants.dart';
46
import 'lib_pidcore_credential_data_source.dart';
57

8+
@singleton
69
class LocalClaimDataSource {
710
LibPolygonIdCoreCredentialDataSource _libPolygonIdCoreCredentialDataSource;
811

12+
final _cache = <String, List<String>>{};
13+
914
LocalClaimDataSource(this._libPolygonIdCoreCredentialDataSource);
1015

1116
Future<List<String>> getAuthClaim({
@@ -14,13 +19,23 @@ class LocalClaimDataSource {
1419
}) {
1520
final nonce = authClaimNonce ?? DEFAULT_AUTH_CLAIM_NONCE;
1621

22+
final cacheKey = _cacheKey(publicKey.toString(), nonce);
23+
if (_cache.containsKey(cacheKey)) {
24+
return Future.value(_cache[cacheKey]!);
25+
}
26+
1727
String authClaimSchema = AUTH_CLAIM_SCHEMA;
1828
String authClaim = _libPolygonIdCoreCredentialDataSource.issueClaim(
1929
schema: authClaimSchema,
2030
nonce: nonce,
2131
publicKey: publicKey,
2232
);
2333
List<String> children = List.from(jsonDecode(authClaim));
34+
35+
_cache[cacheKey] = children;
36+
2437
return Future.value(children);
2538
}
2639
}
40+
41+
String _cacheKey(String publicKey, String nonce) => publicKey + "_" + nonce;

lib/iden3comm/authenticate.dart

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,6 @@ import 'package:polygonid_flutter_sdk/iden3comm/domain/exceptions/iden3comm_exce
5858
import 'package:polygonid_flutter_sdk/iden3comm/domain/exceptions/jwz_exceptions.dart';
5959
import 'package:polygonid_flutter_sdk/iden3comm/domain/use_cases/generate_iden3comm_proof_use_case.dart';
6060
import 'package:polygonid_flutter_sdk/iden3comm/domain/use_cases/get_iden3message_use_case.dart';
61-
import 'package:polygonid_flutter_sdk/identity/data/data_sources/lib_babyjubjub_data_source.dart';
6261
import 'package:polygonid_flutter_sdk/identity/data/data_sources/lib_pidcore_identity_data_source.dart';
6362
import 'package:polygonid_flutter_sdk/identity/data/data_sources/wallet_data_source.dart';
6463
import 'package:polygonid_flutter_sdk/identity/data/dtos/circuit_type.dart';
@@ -88,6 +87,8 @@ import 'package:polygonid_flutter_sdk/proof/gist_proof_cache.dart';
8887
import 'package:polygonid_flutter_sdk/proof/infrastructure/proof_generation_stream_manager.dart';
8988
import 'package:polygonid_flutter_sdk/proof/libs/polygonidcore/pidcore_proof.dart';
9089
import 'package:polygonid_flutter_sdk/sdk/di/injector.dart';
90+
import 'package:poseidon/constants/p1.dart';
91+
import 'package:poseidon/poseidon.dart';
9192
import 'package:sembast/sembast.dart';
9293
import 'package:uuid/uuid.dart';
9394
import 'package:web3dart/crypto.dart';
@@ -1027,11 +1028,9 @@ class Authenticate {
10271028
// Endianness
10281029
BigInt endian = Uint8ArrayUtils.leBuff2int(sha);
10291030

1030-
String qNormalized = endian.qNormalize().toString();
1031+
BigInt qNormalized = endian.qNormalize();
10311032

1032-
var libBabyJubJub = getItSdk<LibBabyJubJubDataSource>();
1033-
1034-
String authChallenge = await libBabyJubJub.hashPoseidon(qNormalized);
1033+
String authChallenge = poseidon1([qNormalized]).toString();
10351034

10361035
String signature = await signMessage(
10371036
privateKey: privateKeyBytes,
@@ -1140,28 +1139,30 @@ class Authenticate {
11401139
publicKey: publicKey,
11411140
);
11421141
authClaim = List.from(jsonDecode(issuedAuthClaim));
1143-
var libBabyJubJub = getItSdk<LibBabyJubJubDataSource>();
1144-
String hashIndex = await libBabyJubJub.hashPoseidon4(
1145-
authClaim[0],
1146-
authClaim[1],
1147-
authClaim[2],
1148-
authClaim[3],
1149-
);
1150-
String hashValue = await libBabyJubJub.hashPoseidon4(
1151-
authClaim[4],
1152-
authClaim[5],
1153-
authClaim[6],
1154-
authClaim[7],
1155-
);
1156-
String hashClaimNode = await libBabyJubJub.hashPoseidon3(
1157-
hashIndex, hashValue, BigInt.one.toString());
1142+
BigInt hashIndex = poseidon4([
1143+
BigInt.parse(authClaim[0]),
1144+
BigInt.parse(authClaim[1]),
1145+
BigInt.parse(authClaim[2]),
1146+
BigInt.parse(authClaim[3]),
1147+
]);
1148+
BigInt hashValue = poseidon4([
1149+
BigInt.parse(authClaim[4]),
1150+
BigInt.parse(authClaim[5]),
1151+
BigInt.parse(authClaim[6]),
1152+
BigInt.parse(authClaim[7]),
1153+
]);
1154+
BigInt hashClaimNode = poseidon3([
1155+
hashIndex,
1156+
hashValue,
1157+
BigInt.one,
1158+
]);
11581159
NodeEntity authClaimNode = NodeEntity(
11591160
children: [
1160-
HashEntity.fromBigInt(BigInt.parse(hashIndex)),
1161-
HashEntity.fromBigInt(BigInt.parse(hashValue)),
1161+
HashEntity.fromBigInt(hashIndex),
1162+
HashEntity.fromBigInt(hashValue),
11621163
HashEntity.fromBigInt(BigInt.one),
11631164
],
1164-
hash: HashEntity.fromBigInt(BigInt.parse(hashClaimNode)),
1165+
hash: HashEntity.fromBigInt(hashClaimNode),
11651166
type: NodeType.leaf,
11661167
);
11671168

lib/iden3comm/data/repositories/iden3comm_repository_impl.dart

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -27,21 +27,20 @@ import 'package:polygonid_flutter_sdk/iden3comm/domain/entities/proof/response/i
2727
import 'package:polygonid_flutter_sdk/iden3comm/domain/exceptions/iden3comm_exceptions.dart';
2828
import 'package:polygonid_flutter_sdk/iden3comm/domain/repositories/iden3comm_repository.dart';
2929
import 'package:polygonid_flutter_sdk/iden3comm/domain/use_cases/get_iden3message_use_case.dart';
30-
import 'package:polygonid_flutter_sdk/identity/data/data_sources/lib_babyjubjub_data_source.dart';
3130
import 'package:polygonid_flutter_sdk/identity/data/mappers/q_mapper.dart';
3231
import 'package:polygonid_flutter_sdk/identity/domain/entities/identity_entity.dart';
3332
import 'package:polygonid_flutter_sdk/proof/data/dtos/gist_mtproof_entity.dart';
3433
import 'package:polygonid_flutter_sdk/proof/data/dtos/mtproof_dto.dart';
3534
import 'package:polygonid_flutter_sdk/proof/data/mappers/gist_mtproof_mapper.dart';
35+
import 'package:poseidon/poseidon.dart';
36+
import 'package:poseidon/poseidon/poseidon.dart';
3637
import 'package:uuid/uuid.dart';
3738

3839
class Iden3commRepositoryImpl extends Iden3commRepository {
3940
final Iden3MessageDataSource _iden3messageDataSource;
4041
final RemoteIden3commDataSource _remoteIden3commDataSource;
4142
final LibPolygonIdCoreIden3commDataSource
4243
_libPolygonIdCoreIden3commDataSource;
43-
final LibBabyJubJubDataSource
44-
_libBabyJubJubDataSource; // TODO move bjj DS to common
4544
final AuthResponseMapper _authResponseMapper;
4645
final AuthProofMapper _authProofMapper;
4746
final GistMTProofMapper _gistProofMapper;
@@ -54,7 +53,6 @@ class Iden3commRepositoryImpl extends Iden3commRepository {
5453
this._iden3messageDataSource,
5554
this._remoteIden3commDataSource,
5655
this._libPolygonIdCoreIden3commDataSource,
57-
this._libBabyJubJubDataSource,
5856
this._authResponseMapper,
5957
this._authProofMapper,
6058
this._gistProofMapper,
@@ -174,9 +172,9 @@ class Iden3commRepositoryImpl extends Iden3commRepository {
174172
}
175173

176174
@override
177-
Future<String> getChallenge({required String message}) {
175+
Future<String> getChallenge({required String message}) async {
178176
final q = _qMapper.mapFrom(message);
179-
return _libBabyJubJubDataSource.hashPoseidon(q);
177+
return poseidon1([BigInt.parse(q)]).toString();
180178
}
181179

182180
@override

lib/iden3comm/domain/use_cases/check_profile_and_did_current_env.dart

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,11 @@ class CheckProfileAndDidCurrentEnvUseCase
3939
);
4040

4141
@override
42-
Future<void> execute(
43-
{required CheckProfileAndDidCurrentEnvParam param}) async {
42+
Future<void> execute({
43+
required CheckProfileAndDidCurrentEnvParam param,
44+
}) async {
4445
try {
46+
final timestamp = DateTime.now().millisecondsSinceEpoch;
4547
// check if profile is valid, it will throw an exception if not
4648
await _checkProfileValidityUseCase.execute(
4749
param: CheckProfileValidityParam(profileNonce: param.profileNonce));
@@ -69,8 +71,8 @@ class CheckProfileAndDidCurrentEnvUseCase
6971
);
7072
}
7173

72-
logger().i(
73-
"[CheckProfileAndDidCurrentEnvUseCase] Profile ${param.profileNonce} and private key are valid for current env");
74+
logger().d(
75+
"[CheckProfileAndDidCurrentEnvUseCase] Profile ${param.profileNonce} and private key are valid for current env in ${DateTime.now().millisecondsSinceEpoch - timestamp} ms");
7476
_stacktraceManager.addTrace(
7577
"[CheckProfileAndDidCurrentEnvUseCase] Profile ${param.profileNonce} and private key are valid for current env");
7678
} on PolygonIdSDKException catch (_) {

0 commit comments

Comments
 (0)