-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathStrKey.java
More file actions
692 lines (621 loc) · 21.5 KB
/
StrKey.java
File metadata and controls
692 lines (621 loc) · 21.5 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
package org.stellar.sdk;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Optional;
import lombok.NonNull;
import lombok.Value;
import org.stellar.sdk.exception.UnexpectedException;
/**
* StrKey is a helper class that allows encoding and decoding Stellar keys to/from strings, i.e.
* between their binary and string (i.e. "GABCD...", etc.) representations.
*/
public class StrKey {
private static final BigInteger UINT64_MAX = new BigInteger("18446744073709551615");
private static final byte[] b32Table = decodingTable();
private static final Base32 base32Codec = Base32Factory.getInstance();
/**
* Encodes raw data to strkey ed25519 public key (G...)
*
* @param data data to encode
* @return "G..." representation of the key
*/
public static String encodeEd25519PublicKey(byte[] data) {
char[] encoded = encodeCheck(VersionByte.ACCOUNT_ID, data);
return String.valueOf(encoded);
}
/**
* Decodes strkey ed25519 public key (G...) to raw data
*
* @param data data to decode
* @return raw bytes
*/
public static byte[] decodeEd25519PublicKey(String data) {
return decodeCheck(VersionByte.ACCOUNT_ID, data.toCharArray());
}
/**
* Checks validity of Stellar account ID (G...).
*
* @param accountID the account ID to check
* @return true if the given Stellar account ID is a valid Stellar account ID, false otherwise
*/
public static boolean isValidEd25519PublicKey(String accountID) {
try {
decodeEd25519PublicKey(accountID);
return true;
} catch (Exception e) {
return false;
}
}
/**
* Encodes raw data to strkey ed25519 seed in char array (S...)
*
* @param data data to encode
* @return "S..." representation of the key in char array
*/
public static char[] encodeEd25519SecretSeed(byte[] data) {
return encodeCheck(VersionByte.SEED, data);
}
/**
* Decodes strkey ed25519 seed char array (S...) to raw bytes
*
* @param data data to decode
* @return raw bytes
*/
public static byte[] decodeEd25519SecretSeed(char[] data) {
return decodeCheck(VersionByte.SEED, data);
}
/**
* Checks validity of seed (S...).
*
* @param seed the seed to check
* @return true if the given seed is a valid seed, false otherwise
*/
public static boolean isValidEd25519SecretSeed(char[] seed) {
try {
decodeEd25519SecretSeed(seed);
return true;
} catch (Exception e) {
return false;
}
}
/**
* Encodes raw data to strkey PreAuthTx (T...)
*
* @param data data to encode
* @return "T..." representation of the key
*/
public static String encodePreAuthTx(byte[] data) {
char[] encoded = encodeCheck(VersionByte.PRE_AUTH_TX, data);
return String.valueOf(encoded);
}
/**
* Decodes strkey PreAuthTx (T...) to raw bytes
*
* @param data data to decode
* @return raw bytes
*/
public static byte[] decodePreAuthTx(String data) {
return decodeCheck(VersionByte.PRE_AUTH_TX, data.toCharArray());
}
/**
* Checks validity of PreAuthTx (T...).
*
* @param preAuthTx the PreAuthTx to check
* @return true if the given PreAuthTx is a valid PreAuthTx, false otherwise
*/
public static boolean isValidPreAuthTx(String preAuthTx) {
try {
decodePreAuthTx(preAuthTx);
return true;
} catch (Exception e) {
return false;
}
}
/**
* Encodes raw data to strkey SHA256 hash (X...)
*
* @param data data to encode
* @return "X..." representation of the key
*/
public static String encodeSha256Hash(byte[] data) {
char[] encoded = encodeCheck(VersionByte.SHA256_HASH, data);
return String.valueOf(encoded);
}
/**
* Decodes strkey SHA256 hash (X...) to raw bytes
*
* @param data data to decode
* @return raw bytes
*/
public static byte[] decodeSha256Hash(String data) {
return decodeCheck(VersionByte.SHA256_HASH, data.toCharArray());
}
/**
* Checks validity of SHA256 hash (X...).
*
* @param sha256Hash the SHA256 hash to check
* @return true if the given SHA256 hash is a valid SHA256 hash, false otherwise
*/
public static boolean isValidSha256Hash(String sha256Hash) {
try {
decodeSha256Hash(sha256Hash);
return true;
} catch (Exception e) {
return false;
}
}
/**
* Encodes raw data to strkey signed payload (P...)
*
* @param data data to encode
* @return "P..." representation of the key
*/
public static String encodeSignedPayload(byte[] data) {
char[] encoded = encodeCheck(VersionByte.SIGNED_PAYLOAD, data);
return String.valueOf(encoded);
}
/**
* Decodes strkey signed payload (P...) to raw bytes.
*
* @param data data to decode
* @return raw bytes
*/
public static byte[] decodeSignedPayload(String data) {
return decodeCheck(VersionByte.SIGNED_PAYLOAD, data.toCharArray());
}
/**
* Checks validity of signed payload (P...).
*
* @param signedPayload the signed payload to check
* @return true if the given signed payload is a valid signed payload, false otherwise
*/
public static boolean isValidSignedPayload(String signedPayload) {
try {
decodeSignedPayload(signedPayload);
return true;
} catch (Exception e) {
return false;
}
}
/**
* Encodes raw data to strkey contract ID (C...)
*
* @param data data to encode
* @return "C..." representation of the key
*/
public static String encodeContract(byte[] data) {
char[] encoded = encodeCheck(VersionByte.CONTRACT, data);
return String.valueOf(encoded);
}
/**
* Decodes strkey contract ID (C...) to raw bytes.
*
* @param data data to decode
* @return raw bytes
*/
public static byte[] decodeContract(String data) {
return decodeCheck(VersionByte.CONTRACT, data.toCharArray());
}
/**
* Checks validity of contract (C...) address.
*
* @param contractId the contract ID to check
* @return true if the given contract ID is a valid contract ID, false otherwise
*/
public static boolean isValidContract(String contractId) {
try {
decodeContract(contractId);
return true;
} catch (Exception e) {
return false;
}
}
/**
* Encodes raw data to strkey liquidity pool ID (L...)
*
* @param data data to encode
* @return "L..." representation of the key
*/
public static String encodeLiquidityPool(byte[] data) {
char[] encoded = encodeCheck(VersionByte.LIQUIDITY_POOL, data);
return String.valueOf(encoded);
}
/**
* Decodes strkey liquidity pool ID (L...) to raw bytes.
*
* @param data data to decode
* @return raw bytes
*/
public static byte[] decodeLiquidityPool(String data) {
return decodeCheck(VersionByte.LIQUIDITY_POOL, data.toCharArray());
}
/**
* Checks validity of liquidity pool (L...) address.
*
* @param liquidityPoolId the liquidity pool ID to check
* @return true if the given liquidity pool ID is a valid liquidity pool ID, false otherwise
*/
public static boolean isValidLiquidityPool(String liquidityPoolId) {
try {
decodeLiquidityPool(liquidityPoolId);
return true;
} catch (Exception e) {
return false;
}
}
/**
* Encodes raw data to strkey claimable balance ID (B...)
*
* @param data data to encode
* @return "B..." representation of the key
*/
public static String encodeClaimableBalance(byte[] data) {
char[] encoded = encodeCheck(VersionByte.CLAIMABLE_BALANCE, data);
return String.valueOf(encoded);
}
/**
* Decodes strkey claimable balance ID (B...) to raw bytes.
*
* @param data data to decode
* @return raw bytes
*/
public static byte[] decodeClaimableBalance(String data) {
return decodeCheck(VersionByte.CLAIMABLE_BALANCE, data.toCharArray());
}
/**
* Checks validity of claimable balance (B...) address.
*
* @param claimableBalanceId the claimable balance ID to check
* @return true if the given claimable balance ID is a valid claimable balance ID, false otherwise
*/
public static boolean isValidClaimableBalance(String claimableBalanceId) {
try {
decodeClaimableBalance(claimableBalanceId);
return true;
} catch (Exception e) {
return false;
}
}
/**
* Encodes raw data to strkey Stellar med25519 public key (M...)
*
* @param data data to encode
* @return "M..." representation of the key
*/
public static String encodeMed25519PublicKey(byte[] data) {
char[] encoded = encodeCheck(VersionByte.MED25519_PUBLIC_KEY, data);
return String.valueOf(encoded);
}
/**
* Decodes strkey Stellar med25519 public key (M...) to raw bytes
*
* @param data data to decode
* @return raw bytes
*/
public static byte[] decodeMed25519PublicKey(String data) {
return decodeCheck(VersionByte.MED25519_PUBLIC_KEY, data.toCharArray());
}
/**
* Checks validity of med25519 public key (M...).
*
* @param med25519PublicKey the med25519 public key to check
* @return true if the given med25519 public key is a valid med25519 public key, false otherwise
*/
public static boolean isValidMed25519PublicKey(String med25519PublicKey) {
try {
decodeMed25519PublicKey(med25519PublicKey);
return true;
} catch (Exception e) {
return false;
}
}
static VersionByte decodeVersionByte(String data) {
byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
byte[] decoded = base32decode(dataBytes);
byte decodedVersionByte = decoded[0];
Optional<VersionByte> versionByteOptional = VersionByte.findByValue(decodedVersionByte);
if (!versionByteOptional.isPresent()) {
throw new IllegalArgumentException("Version byte is invalid");
}
return versionByteOptional.get();
}
static char[] encodeCheck(VersionByte versionByte, byte[] data) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(versionByte.getValue());
try {
outputStream.write(data);
} catch (IOException e) {
throw new UnexpectedException(e);
}
byte[] payload = outputStream.toByteArray();
byte[] checksum = StrKey.calculateChecksum(payload);
try {
outputStream.write(checksum);
} catch (IOException e) {
throw new UnexpectedException(e);
}
byte[] unencoded = outputStream.toByteArray();
byte[] encodedBytes = base32Codec.encode(unencoded);
byte[] unpaddedEncodedBytes = removeBase32Padding(encodedBytes);
char[] charsEncoded = bytesToChars(unpaddedEncodedBytes);
if (VersionByte.SEED != versionByte) {
return charsEncoded;
}
// Erase all data from memory
Arrays.fill(unencoded, (byte) 0);
Arrays.fill(payload, (byte) 0);
Arrays.fill(checksum, (byte) 0);
Arrays.fill(encodedBytes, (byte) 0);
Arrays.fill(unpaddedEncodedBytes, (byte) 0);
return charsEncoded;
}
static byte[] decodeCheck(VersionByte versionByte, char[] encoded) {
byte[] bytes = new byte[encoded.length];
for (int i = 0; i < encoded.length; i++) {
bytes[i] = (byte) encoded[i];
}
// The minimal binary decoded length is 3 bytes (version byte and 2-byte CRC) which,
// in unpadded base32 (since each character provides 5 bits) corresponds to ceiling(8*3/5) = 5
if (bytes.length < 5) {
throw new IllegalArgumentException("Encoded char array must have a length of at least 5.");
}
int leftoverBits = (bytes.length * 5) % 8;
// 1. Make sure there is no full unused leftover byte at the end
// (i.e. there shouldn't be 5 or more leftover bits)
if (leftoverBits >= 5) {
throw new IllegalArgumentException("Encoded char array has leftover character.");
}
if (leftoverBits > 0) {
byte lastChar = bytes[bytes.length - 1];
byte decodedLastChar = b32Table[lastChar];
byte leftoverBitsMask = (byte) (0x0f >> (4 - leftoverBits));
if ((decodedLastChar & leftoverBitsMask) != 0) {
throw new IllegalArgumentException("Unused bits should be set to 0.");
}
}
byte[] decoded = base32decode(bytes);
byte decodedVersionByte = decoded[0];
VersionByte decodedVersionByteEnum =
VersionByte.findByValue(decodedVersionByte)
.orElseThrow(() -> new IllegalArgumentException("Version byte is invalid"));
byte[] payload = Arrays.copyOfRange(decoded, 0, decoded.length - 2);
byte[] data = Arrays.copyOfRange(payload, 1, payload.length);
byte[] checksum = Arrays.copyOfRange(decoded, decoded.length - 2, decoded.length);
// Check the data length
switch (decodedVersionByteEnum) {
case SIGNED_PAYLOAD:
if (data.length < 32 + 4 + 4 || data.length > 32 + 4 + 64) {
throw new IllegalArgumentException(
"Invalid data length, the length should be between 40 and 100 bytes, got "
+ data.length);
}
break;
case MED25519_PUBLIC_KEY:
if (data.length != 32 + 8) {
throw new IllegalArgumentException(
"Invalid data length, expected 40 bytes, got " + data.length);
}
break;
case CLAIMABLE_BALANCE:
if (data.length != 32 + 1) {
// If we are encoding a claimable balance, the binary bytes of the key has a length of
// 33-bytes:
// 1-byte value indicating the type of claimable balance, where 0x00 maps to V0, and a
// 32-byte SHA256 hash.
throw new IllegalArgumentException(
"Invalid data length, expected 33 bytes, got " + data.length);
}
break;
default:
if (data.length != 32) {
throw new IllegalArgumentException(
"Invalid data length, expected 32 bytes, got " + data.length);
}
break;
}
if (decodedVersionByteEnum != versionByte) {
throw new IllegalArgumentException("Version byte mismatch");
}
byte[] expectedChecksum = StrKey.calculateChecksum(payload);
if (!Arrays.equals(expectedChecksum, checksum)) {
throw new IllegalArgumentException("Checksum invalid");
}
if (VersionByte.SIGNED_PAYLOAD.getValue() == decodedVersionByte) {
byte[] lengthBytes = Arrays.copyOfRange(data, 32, 36);
int payloadLength = ByteBuffer.wrap(lengthBytes).getInt();
// Validate payload length: must be between 1 and 64 bytes
if (payloadLength < 1 || payloadLength > 64) {
throw new IllegalArgumentException(
"Invalid Ed25519 Signed Payload Key, payload length must be between 1 and 64, got "
+ payloadLength);
}
int padding = (4 - payloadLength % 4) % 4;
if (data.length % 4 != 0 || payloadLength + padding != data.length - 36) {
throw new IllegalArgumentException("Invalid Ed25519 Signed Payload Key");
}
// Validate padding bytes are all zeros
for (int i = 36 + payloadLength; i < data.length; i++) {
if (data[i] != 0) {
throw new IllegalArgumentException(
"Invalid Ed25519 Signed Payload Key, padding bytes must be zero");
}
}
}
if (VersionByte.SEED.getValue() == decodedVersionByte) {
Arrays.fill(bytes, (byte) 0);
Arrays.fill(decoded, (byte) 0);
Arrays.fill(payload, (byte) 0);
}
return data;
}
private static byte[] calculateChecksum(byte[] bytes) {
// This code calculates CRC16-XModem checksum
// Ported from https://github.com/alexgorbatchev/node-crc
int crc = 0x0000;
int count = bytes.length;
int i = 0;
int code;
while (count > 0) {
code = crc >>> 8 & 0xFF;
code ^= bytes[i++] & 0xFF;
code ^= code >>> 4;
crc = crc << 8 & 0xFFFF;
crc ^= code;
code = code << 5 & 0xFFFF;
crc ^= code;
code = code << 7 & 0xFFFF;
crc ^= code;
count--;
}
// little-endian
return new byte[] {(byte) crc, (byte) (crc >>> 8)};
}
private static byte[] decodingTable() {
byte[] table = new byte[256];
for (int i = 0; i < 256; i++) {
table[i] = (byte) 0xff;
}
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
for (int i = 0; i < alphabet.length(); i++) {
table[alphabet.charAt(i)] = (byte) i;
}
return table;
}
private static byte[] removeBase32Padding(byte[] data) {
// Calculate the length of unpadded data
int unpaddedLength = data.length;
while (unpaddedLength > 0 && data[unpaddedLength - 1] == '=') {
unpaddedLength--;
}
// Create a copy of the data without padding bytes
return Arrays.copyOf(data, unpaddedLength);
}
private static char[] bytesToChars(byte[] data) {
char[] chars = new char[data.length];
for (int i = 0; i < data.length; i++) {
chars[i] = (char) (data[i] & 0xFF);
}
return chars;
}
private static byte[] base32decode(byte[] data) {
// Apache commons codec Base32 class will auto remove the illegal characters, this is
// what we don't want, so we need to check the data before decoding
if (!isInAlphabet(data)) {
throw new IllegalArgumentException("Invalid base32 encoded string");
}
return base32Codec.decode(data);
}
private static boolean isInAlphabet(final byte[] arrayOctet) {
for (final byte octet : arrayOctet) {
if (!(octet >= 0 && octet < b32Table.length && b32Table[octet] != -1)) {
return false;
}
}
return true;
}
@Value
static class RawMuxedAccountStrKeyParameter {
byte @NonNull [] ed25519;
@NonNull BigInteger id;
}
static byte[] toRawMuxedAccountStrKey(RawMuxedAccountStrKeyParameter parameter) {
byte[] ed25519Bytes = parameter.getEd25519();
if (ed25519Bytes.length != 32) {
throw new IllegalArgumentException(
"Muxed account ed25519 bytes must be 32 bytes long, got " + ed25519Bytes.length);
}
if (parameter.getId().compareTo(BigInteger.ZERO) < 0
|| parameter.getId().compareTo(UINT64_MAX) > 0) {
throw new IllegalArgumentException(
"Muxed account ID must be between 0 and 2^64 - 1 inclusive");
}
// Get the 64-bit ID. This is the critical part of the explanation.
//
// THE KEY INSIGHT: Why using .longValue() is safe for a uint64
// --------------------------------------------------------------------
//
// The Goal: We need to get the 8-byte binary representation of an uint64.
// The Problem: A Java `long` is a *signed* 64-bit integer.
// - `uint64` range: 0 to 2^64 - 1
// - `long` range: -2^63 to 2^63 - 1
// A `uint64` can hold values larger than a `long`'s maximum positive value.
//
// The Solution: We focus on the underlying *bit pattern*, not the numerical interpretation.
//
// When we serialize data, we only care about the sequence of bits.
// - `getNumber()` returns a BigInteger, which correctly holds the full uint64 value.
// - `.longValue()` extracts the low-order 64 bits from the BigInteger. For an uint64, this is
// all its bits.
//
// Let's consider two cases:
//
// Case A: The uint64 value is small ( < 2^63 ).
// The most significant bit is 0. The `long` will have the same positive value, and the bit
// pattern is identical.
//
// Case B: The uint64 value is large ( >= 2^63 ).
// The most significant bit is 1. When converted to a `long`, Java interprets this bit as a
// sign bit,
// making the `long`'s numerical value negative. HOWEVER, the underlying 64-bit pattern in
// memory remains IDENTICAL
// to the original uint64's bit pattern.
//
// Example for Case B:
// - Let uint64 be 2^64 - 1 (all 64 bits are '1').
// - Its binary representation is 0xFFFF_FFFF_FFFF_FFFF.
// - `.longValue()` will produce a `long` with the value -1.
// - The binary representation of -1L in Java (using two's complement) is also
// 0xFFFF_FFFF_FFFF_FFFF.
//
// The bit patterns are the same!
//
// Since `ByteBuffer.putLong()` simply writes the 64-bit pattern of the given long into the
// buffer,
// it correctly serializes the original uint64 value into 8 bytes, regardless of whether Java
// interpreted the intermediate `long` as positive or negative.
long idLong = parameter.getId().longValue();
return ByteBuffer.allocate(ed25519Bytes.length + 8).put(ed25519Bytes).putLong(idLong).array();
}
static RawMuxedAccountStrKeyParameter fromRawMuxedAccountStrKey(byte @NonNull [] data) {
if (data.length != 40) {
throw new IllegalArgumentException(
"Muxed account bytes must be 40 bytes long, got " + data.length);
}
ByteBuffer buffer = ByteBuffer.wrap(data);
byte[] ed25519Bytes = new byte[32];
buffer.get(ed25519Bytes);
byte[] idBytes = new byte[8];
buffer.get(idBytes);
return new RawMuxedAccountStrKeyParameter(ed25519Bytes, new BigInteger(1, idBytes));
}
enum VersionByte {
ACCOUNT_ID((byte) (6 << 3)), // G
MED25519_PUBLIC_KEY((byte) (12 << 3)), // M
SEED((byte) (18 << 3)), // S
PRE_AUTH_TX((byte) (19 << 3)), // T
SHA256_HASH((byte) (23 << 3)), // X
SIGNED_PAYLOAD((byte) (15 << 3)), // P
CONTRACT((byte) (2 << 3)), // C
LIQUIDITY_POOL((byte) (11 << 3)), // L
CLAIMABLE_BALANCE((byte) (1 << 3)); // B
private final byte value;
VersionByte(byte value) {
this.value = value;
}
public static Optional<VersionByte> findByValue(byte value) {
for (VersionByte versionByte : values()) {
if (value == versionByte.value) {
return Optional.of(versionByte);
}
}
return Optional.empty();
}
public int getValue() {
return value;
}
}
}