-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcommunity_identifier.dart
66 lines (50 loc) · 2.12 KB
/
community_identifier.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import 'dart:convert';
import 'package:base58check/base58.dart';
import 'package:base58check/base58check.dart';
import 'package:flutter/foundation.dart';
import 'package:ew_polkadart/encointer_types.dart' as et;
import 'package:encointer_wallet/utils/format.dart';
/// CommunityIdentifier consisting of a geohash and a 4-bytes crc code.
class CommunityIdentifier {
const CommunityIdentifier(this.geohash, this.digest);
factory CommunityIdentifier.fromFmtString(String cid) {
const codec = Base58Codec(Base58CheckCodec.BITCOIN_ALPHABET);
return CommunityIdentifier(utf8.encode(cid.substring(0, 5)), codec.decode(cid.substring(5)));
}
factory CommunityIdentifier.fromPolkadart(et.CommunityIdentifier cid) {
return CommunityIdentifier(cid.geohash, cid.digest);
}
// JS-passes these values as hex-strings, but this would be more complicated to handle in dart.
factory CommunityIdentifier.fromJson(Map<String, dynamic> json) =>
CommunityIdentifier(Fmt.hexToBytes(json['geohash'] as String), Fmt.hexToBytes(json['digest'] as String));
Map<String, dynamic> toJson() => <String, dynamic>{
'geohash': Fmt.bytesToHex(geohash),
'digest': Fmt.bytesToHex(digest),
};
// [u8; 5]
final List<int> geohash;
// [u8; 4]
final List<int> digest;
@override
String toString() {
return jsonEncode(this);
}
String toFmtString() {
const codec = Base58Codec(Base58CheckCodec.BITCOIN_ALPHABET);
return utf8.decode(geohash) + codec.encode(digest);
}
et.CommunityIdentifier toPolkadart() {
return et.CommunityIdentifier(geohash: geohash, digest: digest);
}
// By default, the dart `==` operator returns only true iff both variables point to the same instance. We want to
// override this behaviour, such that it is also true if the instances contain the same values.
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is CommunityIdentifier &&
runtimeType == other.runtimeType &&
listEquals(geohash, other.geohash) &&
listEquals(digest, other.digest);
@override
int get hashCode => toFmtString().hashCode;
}