|
@@ -1,7 +1,8 @@
|
|
|
import 'dart:convert' show utf8;
|
|
import 'dart:convert' show utf8;
|
|
|
import 'dart:typed_data';
|
|
import 'dart:typed_data';
|
|
|
-
|
|
|
|
|
import 'package:convert/convert.dart' show hex;
|
|
import 'package:convert/convert.dart' show hex;
|
|
|
|
|
+import "package:pointycastle/digests/keccak.dart";
|
|
|
|
|
+
|
|
|
|
|
|
|
|
bool isHexPrefixed(String str) {
|
|
bool isHexPrefixed(String str) {
|
|
|
ArgumentError.checkNotNull(str);
|
|
ArgumentError.checkNotNull(str);
|
|
@@ -221,3 +222,56 @@ String dec2hex(String decString) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+/// ----- to Hash -----
|
|
|
|
|
+/// 注意:Hash256 和 Keccak256 其实不一样,
|
|
|
|
|
+/// 但由于最早接触 Ethereum 相关代码,其中 Hash 使用的是 Keccak256,
|
|
|
|
|
+/// 造成App其他地方的 Hash 也都沿用了 Keccak256。
|
|
|
|
|
+/// 历史原因,不做修改。[2023-12-15 James.Zhang]
|
|
|
|
|
+
|
|
|
|
|
+String toHash(String anyString) {
|
|
|
|
|
+ return toKeccak256(anyString);
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+String toKeccak256(String anyString, [int bitLength = 256]) {
|
|
|
|
|
+ var keccak = KeccakDigest(bitLength);
|
|
|
|
|
+ keccak.update(
|
|
|
|
|
+ Uint8List.fromList(anyString.codeUnits),
|
|
|
|
|
+ 0,
|
|
|
|
|
+ anyString.codeUnits.length,
|
|
|
|
|
+ );
|
|
|
|
|
+
|
|
|
|
|
+ var out = Uint8List(bitLength ~/ 8);
|
|
|
|
|
+ keccak.doFinal(out, 0);
|
|
|
|
|
+
|
|
|
|
|
+ return _uint8ListToHex(out);
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// Character `0`.
|
|
|
|
|
+const int _zero = 0x30;
|
|
|
|
|
+/// Character `a`.
|
|
|
|
|
+const int _a = 0x61;
|
|
|
|
|
+
|
|
|
|
|
+String _uint8ListToHex(List<int> bytes) {
|
|
|
|
|
+ final buffer = Uint8List(bytes.length * 2);
|
|
|
|
|
+
|
|
|
|
|
+ int bufferIndex = 0;
|
|
|
|
|
+ for (var i = 0; i < bytes.length; i++) {
|
|
|
|
|
+ var byte = bytes[i];
|
|
|
|
|
+
|
|
|
|
|
+ // The bitwise arithmetic here is equivalent to `byte ~/ 16` and `byte % 16`
|
|
|
|
|
+ // for valid byte values, but is easier for dart2js to optimize given that
|
|
|
|
|
+ // it can't prove that [byte] will always be positive.
|
|
|
|
|
+ buffer[bufferIndex++] = _codeUnitForDigit((byte & 0xF0) >> 4);
|
|
|
|
|
+ buffer[bufferIndex++] = _codeUnitForDigit(byte & 0x0F);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ return String.fromCharCodes(buffer);
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+/// Returns the ASCII/Unicode code unit corresponding to the hexadecimal digit
|
|
|
|
|
+/// [digit].
|
|
|
|
|
+int _codeUnitForDigit(int digit) =>
|
|
|
|
|
+ digit < 10 ? digit + _zero : digit + _a - 10;
|
|
|
|
|
+
|