-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathTezosGateway.java
More file actions
2565 lines (2082 loc) · 88.3 KB
/
TezosGateway.java
File metadata and controls
2565 lines (2082 loc) · 88.3 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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package milfont.com.tezosj.data;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static milfont.com.tezosj.helper.Encoder.HEX;
import static milfont.com.tezosj.helper.Constants.UTEZ;
import static milfont.com.tezosj.helper.Constants.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.Object;
import milfont.com.tezosj.helper.Base58Check;
import milfont.com.tezosj.helper.Global;
import milfont.com.tezosj.helper.MySodium;
import milfont.com.tezosj.model.BatchTransactionItem;
import milfont.com.tezosj.model.BatchTransactionItemIndexSorter;
import milfont.com.tezosj.model.EncKeys;
import milfont.com.tezosj.model.SignedOperationGroup;
import milfont.com.tezosj.model.TezosWallet;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class TezosGateway
{
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final MediaType textPlainMT = MediaType.parse("text/plain; charset=utf-8");
private static final Integer HTTP_TIMEOUT = 20;
private static MySodium sodium = null;
public TezosGateway()
{
SecureRandom rand = new SecureRandom();
int n = rand.nextInt(1000000) + 1;
TezosGateway.sodium = new MySodium(String.valueOf(n));
}
public static MySodium getSodium()
{
return sodium;
}
// Sends request for Tezos node.
private Object query(String endpoint, String data) throws Exception
{
JSONObject result = null;
Boolean methodPost = false;
Request request = null;
Proxy proxy = null;
SSLContext sslcontext = null;
// Initializes a single shared instance of okHttp client (and builder).
Global.initOkhttp();
OkHttpClient client = Global.myOkhttpClient;
Builder myBuilder = Global.myOkhttpBuilder;
final MediaType MEDIA_PLAIN_TEXT_JSON = MediaType.parse("application/json");
String DEFAULT_PROVIDER = Global.defaultProvider;
RequestBody body = RequestBody.create(textPlainMT, DEFAULT_PROVIDER + endpoint);
if(data != null)
{
methodPost = true;
body = RequestBody.create(MEDIA_PLAIN_TEXT_JSON, data.getBytes());
}
if(methodPost == false)
{
request = new Request.Builder().url(DEFAULT_PROVIDER + endpoint).build();
}
else
{
request = new Request.Builder().url(DEFAULT_PROVIDER + endpoint).addHeader("Content-Type", "text/plain")
.post(body).build();
}
// If user specified to ignore invalid certificates.
if(Global.ignoreInvalidCertificates)
{
sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[]
{ new X509TrustManager()
{
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
{
}
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException
{
}
public X509Certificate[] getAcceptedIssuers()
{
return new X509Certificate[0];
}
} }, new java.security.SecureRandom());
myBuilder.sslSocketFactory(sslcontext.getSocketFactory()); // To ignore an invalid certificate.
}
// If user specified a proxy host.
if((Global.proxyHost.length() > 0) && (Global.proxyPort.length() > 0))
{
proxy = new Proxy(Proxy.Type.HTTP,
new InetSocketAddress(Global.proxyHost, Integer.parseInt(Global.proxyPort)));
myBuilder.proxy(proxy); // If behind a firewall/proxy.
}
// Constructs the builder;
myBuilder.connectTimeout(HTTP_TIMEOUT, TimeUnit.SECONDS).writeTimeout(HTTP_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(HTTP_TIMEOUT, TimeUnit.SECONDS).build();
try
{
Response response = client.newCall(request).execute();
String strResponse = response.body().string();
if(isJSONObject(strResponse))
{
result = new JSONObject(strResponse);
}
else
{
if(isJSONArray(strResponse))
{
JSONArray myJSONArray = new JSONArray(strResponse);
result = new JSONObject();
result.put("result", myJSONArray);
}
else
{
// If response is not a JSONObject nor JSONArray...
// (can be a primitive).
result = new JSONObject();
result.put("result", strResponse);
}
}
} catch (Exception e)
{
// If there is a real error...
e.printStackTrace();
result = new JSONObject();
result.put("result", e.toString());
}
return result;
}
// RPC methods.
public JSONObject getHead() throws Exception
{
return (JSONObject) query("/chains/main/blocks/head~2", null);
}
public JSONObject getAccountManagerForBlock(String blockHash, String accountID) throws Exception
{
JSONObject result = (JSONObject) query(
"/chains/main/blocks/" + blockHash + "/context/contracts/" + accountID + "/manager_key", null);
return result;
}
// Gets the balance for a given address.
public JSONObject getBalance(String address) throws Exception
{
return (JSONObject) query("/chains/main/blocks/head~2/context/contracts/" + address + "/balance", null);
}
// Prepares and sends an operation to the Tezos node.
private JSONObject sendOperation(JSONArray operations, EncKeys encKeys) throws Exception
{
JSONObject result = new JSONObject();
JSONObject head = new JSONObject();
String forgedOperationGroup = "";
head = (JSONObject) query("/chains/main/blocks/head~2/header", null);
forgedOperationGroup = forgeOperations(head, operations);
// Check for errors.
if(forgedOperationGroup.toLowerCase().contains("failed") || forgedOperationGroup.toLowerCase().contains("unexpected")
|| forgedOperationGroup.toLowerCase().contains("missing") || forgedOperationGroup.toLowerCase().contains("error"))
{
throw new Exception("Error while forging operation : " + forgedOperationGroup);
}
SignedOperationGroup signedOpGroup = signOperationGroup(forgedOperationGroup, encKeys);
if (signedOpGroup == null) // User cancelled the operation.
{
result.put("result", "There were errors: 'User has cancelled the operation'");
return result;
}
else
{
String operationGroupHash = computeOperationHash(signedOpGroup);
JSONObject appliedOp = applyOperation(head, operations, operationGroupHash, forgedOperationGroup, signedOpGroup);
JSONObject opResult = checkAppliedOperationResults(appliedOp);
if(opResult.get("result").toString().length() == 0)
{
JSONObject injectedOperation = injectOperation(signedOpGroup);
if(isJSONArray(injectedOperation.toString()))
{
if(((JSONObject) ((JSONArray) injectedOperation.get("result")).get(0)).has("error"))
{
String err = (String) ((JSONObject) ((JSONArray) injectedOperation.get("result")).get(0)).get("error");
String reason = "There were errors: '" + err + "'";
result.put("result", reason);
}
else
{
result.put("result", "");
}
if(((JSONObject) ((JSONArray) injectedOperation.get("result")).get(0)).has("Error"))
{
String err = (String) ((JSONObject) ((JSONArray) injectedOperation.get("result")).get(0)).get("Error");
String reason = "There were errors: '" + err + "'";
result.put("result", reason);
}
else
{
result.put("result", "");
}
}
else if(isJSONObject(injectedOperation.toString()))
{
if(injectedOperation.has("result"))
{
if(isJSONArray(injectedOperation.get("result").toString()))
{
if(((JSONObject) ((JSONArray) injectedOperation.get("result")).get(0)).has("error"))
{
String err = (String) ((JSONObject) ((JSONArray) injectedOperation.get("result")).get(0))
.get("error");
String reason = "There were errors: '" + err + "'";
result.put("result", reason);
}
else if(((JSONObject) ((JSONArray) injectedOperation.get("result")).get(0)).has("kind"))
{
if(((JSONObject) ((JSONArray) injectedOperation.get("result")).get(0)).has("msg"))
{
String err = (String) ((JSONObject) ((JSONArray) injectedOperation.get("result")).get(0)).get("msg");
String reason = "There were errors: '" + err + "'";
result.put("result", reason);
}
else
{
result.put("result", "");
}
}
else
{
result.put("result", "");
}
}
else
{
result.put("result", injectedOperation.get("result"));
}
}
else
{
result.put("result", "There were errors.");
}
}
}
else
{
result.put("result", opResult.get("result").toString());
}
}
return result;
}
// Call Tezos RUN_OPERATION.
private JSONObject callRunOperation(JSONArray operations, EncKeys encKeys) throws Exception
{
JSONObject result = new JSONObject();
JSONObject head = new JSONObject();
String forgedOperationGroup = "";
head = (JSONObject) query("/chains/main/blocks/head~2/header", null);
forgedOperationGroup = forgeOperations(head, operations);
// Check for errors.
if(forgedOperationGroup.toLowerCase().contains("failed") || forgedOperationGroup.toLowerCase().contains("unexpected")
|| forgedOperationGroup.toLowerCase().contains("missing") || forgedOperationGroup.toLowerCase().contains("error"))
{
throw new Exception("Error while forging operation : " + forgedOperationGroup);
}
SignedOperationGroup signedOpGroup = signOperationGroupSimulation(forgedOperationGroup, null);
if (signedOpGroup == null) // User cancelled the operation.
{
result.put("result", "There were errors: 'User has cancelled the operation'");
return result;
}
else
{
String operationGroupHash = computeOperationHash(signedOpGroup);
// Call RUN_OPERATIONS.
JSONObject runOp = runOperation(head, operations, operationGroupHash, forgedOperationGroup, signedOpGroup);
result = runOp;
}
return result;
}
// Sends a transaction to the Tezos node.
public JSONObject sendTransaction(String from, String to, BigDecimal amount, BigDecimal fee, String gasLimit,
String storageLimit, EncKeys encKeys)
throws Exception
{
JSONObject result = new JSONObject();
BigDecimal roundedAmount = amount.setScale(6, BigDecimal.ROUND_HALF_UP);
BigDecimal roundedFee = fee.setScale(6, BigDecimal.ROUND_HALF_UP);
JSONArray operations = new JSONArray();
JSONObject revealOperation = new JSONObject();
JSONObject transaction = new JSONObject();
JSONObject head = new JSONObject();
JSONObject account = new JSONObject();
JSONObject parameters = new JSONObject();
JSONArray argsArray = new JSONArray();
Integer counter = 0;
// Check if address has enough funds to do the transfer operation.
JSONObject balance = getBalance(from);
if(balance.has("result"))
{
BigDecimal bdAmount = amount.multiply(BigDecimal.valueOf(UTEZ));
BigDecimal total = new BigDecimal(
((balance.getString("result").replaceAll("\\n", "")).replaceAll("\"", "").replaceAll("'", "")));
if(total.compareTo(bdAmount) < 0) // Returns -1 if value is less than amount.
{
// Not enough funds to do the transfer.
JSONObject returned = new JSONObject();
returned.put("result",
"{ \"result\":\"error\", \"kind\":\"TezosJ_SDK_exception\", \"id\": \"Not enough funds\" }");
return returned;
}
}
if(gasLimit == null)
{
gasLimit = "15400";
}
else
{
if((gasLimit.length() == 0) || (gasLimit.equals("0")))
{
gasLimit = "15400";
}
}
if(storageLimit == null)
{
storageLimit = "300";
}
else
{
if(storageLimit.length() == 0)
{
storageLimit = "300";
}
}
head = new JSONObject(query("/chains/main/blocks/head~2/header", null).toString());
account = getAccountForBlock(head.get("hash").toString(), from);
counter = Integer.parseInt(account.get("counter").toString());
// Append Reveal Operation if needed.
revealOperation = appendRevealOperation(head, encKeys, from, (counter));
if(revealOperation != null)
{
operations.put(revealOperation);
counter = counter + 1;
}
transaction.put("destination", to);
transaction.put("amount", (String.valueOf(roundedAmount.multiply(BigDecimal.valueOf(UTEZ)).toBigInteger())));
transaction.put("storage_limit", storageLimit);
transaction.put("gas_limit", gasLimit);
transaction.put("counter", String.valueOf(counter + 1));
transaction.put("fee", (String.valueOf(roundedFee.multiply(BigDecimal.valueOf(UTEZ)).toBigInteger())));
transaction.put("source", from);
transaction.put("kind", OPERATION_KIND_TRANSACTION);
operations.put(transaction);
result = (JSONObject) sendOperation(operations, encKeys);
return result;
}
// Sends an activate operation to the Tezos node.
public JSONObject activate(String addressToActivate, String secret, EncKeys encKeys) throws Exception
{
// This method will activate a Tezos address. Either through the use of a given "secret"
// (like from a faucet or from the fundraiser), or (if an empty "secret" is provided) through
// sending a tiny amount of tez to the destination address (addressToActivate).
JSONObject result = new JSONObject();
if (secret.isEmpty() == false)
{
JSONArray operations = new JSONArray();
JSONObject transaction = new JSONObject();
transaction.put("kind", "activate_account");
transaction.put("pkh", addressToActivate);
transaction.put("secret", secret);
operations.put(transaction);
result = (JSONObject) sendOperation(operations, encKeys);
}
else
{
BigDecimal amount = new BigDecimal("0.002490");
BigDecimal fee = new BigDecimal("0.002490");
// Get public key hash from encKeys.
byte[] bytePk = encKeys.getEncPublicKeyHash();
byte[] decPkBytes = decryptBytes(bytePk, TezosWallet.getEncryptionKey(encKeys));
StringBuilder builder2 = new StringBuilder();
for(byte decPkByte : decPkBytes)
{
builder2.append((char) (decPkByte));
}
String from = builder2.toString();
result = (JSONObject) sendTransaction(from, addressToActivate, amount, fee, "", "", encKeys);
}
return result;
}
// Sends a reveal operation to the Tezos node.
public JSONObject reveal(String publicKeyHash, String publicKey, EncKeys encKeys) throws Exception
{
JSONObject result = new JSONObject();
JSONArray operations = new JSONArray();
JSONObject transaction = new JSONObject();
JSONObject head = new JSONObject();
JSONObject account = new JSONObject();
Integer counter = 0;
head = new JSONObject(query("/chains/main/blocks/head~2/header", null).toString());
account = getAccountForBlock(head.get("hash").toString(), publicKeyHash);
counter = Integer.parseInt(account.get("counter").toString());
BigDecimal fee = new BigDecimal("0.002490");
BigDecimal roundedFee = fee.setScale(6, BigDecimal.ROUND_HALF_UP);
transaction.put("kind", "reveal");
transaction.put("source", publicKeyHash);
transaction.put("fee", (String.valueOf(roundedFee.multiply(BigDecimal.valueOf(UTEZ)).toBigInteger())));
transaction.put("counter", String.valueOf(counter + 1));
transaction.put("gas_limit", "15400");
transaction.put("storage_limit", "300");
transaction.put("public_key", publicKey);
operations.put(transaction);
result = (JSONObject) sendOperation(operations, encKeys);
return result;
}
private SignedOperationGroup signOperationGroup(String forgedOperation, EncKeys encKeys) throws Exception
{
JSONObject signed =null;
if((Global.ledgerDerivationPath.isEmpty()==false)&&(Global.ledgerTezosFolderPath.isEmpty()==false))
{
System.out.println(Global.CONFIRM_WITH_LEDGER_MESSAGE);
signed = signWithLedger(HEX.decode(forgedOperation), "03");
}
else
{
// Traditional signing.
signed = sign(HEX.decode(forgedOperation), encKeys, "03");
}
if (signed == null) // User cancelled the operation.
{
return null;
}
else
{
// Prepares the object to be returned.
byte[] workBytes = ArrayUtils.addAll(HEX.decode(forgedOperation), HEX.decode((String) signed.get("sig")));
return new SignedOperationGroup(workBytes, (String) signed.get("edsig"), (String) signed.get("sbytes"));
}
}
private SignedOperationGroup signOperationGroupSimulation(String forgedOperation, EncKeys encKeys) throws Exception
{
JSONObject signed = new JSONObject();
byte[] bytes = HEX.decode(forgedOperation);
byte[] sig = new byte[64];
byte[] edsigPrefix = { 9, (byte) 245, (byte) 205, (byte) 134, 18 };
byte[] edsigPrefixedSig = new byte[edsigPrefix.length + sig.length];
edsigPrefixedSig = ArrayUtils.addAll(edsigPrefix, sig);
String edsig = Base58Check.encode(edsigPrefixedSig);
String sbytes = HEX.encode(bytes) + HEX.encode(sig);
signed.put("bytes", HEX.encode(bytes));
signed.put("sig", HEX.encode(sig));
signed.put("edsig", edsig);
signed.put("sbytes", sbytes);
// Prepares the object to be returned.
byte[] workBytes = ArrayUtils.addAll(HEX.decode(forgedOperation), HEX.decode((String) signed.get("sig")));
return new SignedOperationGroup(workBytes, (String) signed.get("edsig"), (String) signed.get("sbytes"));
}
private String forgeOperations(JSONObject blockHead, JSONArray operations) throws Exception
{
JSONObject result = new JSONObject();
result.put("branch", blockHead.get("hash"));
result.put("contents", operations);
return nodeForgeOperations(result.toString());
}
private String nodeForgeOperations(String opGroup) throws Exception
{
JSONObject response = (JSONObject) query("/chains/main/blocks/head~2/helpers/forge/operations", opGroup);
String forgedOperation = (String) response.get("result");
return ((forgedOperation.replaceAll("\\n", "")).replaceAll("\"", "").replaceAll("'", ""));
}
private JSONObject getAccountForBlock(String blockHash, String accountID) throws Exception
{
JSONObject result = new JSONObject();
result = (JSONObject) query("/chains/main/blocks/" + blockHash + "/context/contracts/" + accountID, null);
return result;
}
private String computeOperationHash(SignedOperationGroup signedOpGroup) throws Exception
{
byte[] hash = new byte[32];
int r = sodium.crypto_generichash(hash, hash.length, signedOpGroup.getTheBytes(),
signedOpGroup.getTheBytes().length, signedOpGroup.getTheBytes(), 0);
return Base58Check.encode(hash);
}
private JSONObject nodeApplyOperation(JSONArray payload) throws Exception
{
return (JSONObject) query("/chains/main/blocks/head~2/helpers/preapply/operations", payload.toString());
}
private JSONObject nodeRunOperation(JSONArray payload, String chainId) throws Exception
{
JSONObject operation = new JSONObject();
operation.put("operation", payload.get(0));
operation.put("chain_id", chainId);
return (JSONObject) query("/chains/main/blocks/head~2/helpers/scripts/run_operation", operation.toString());
}
private JSONObject applyOperation(JSONObject head, JSONArray operations, String operationGroupHash,
String forgedOperationGroup, SignedOperationGroup signedOpGroup)
throws Exception
{
JSONObject jsonObject = new JSONObject();
jsonObject.put("protocol", head.get("protocol"));
jsonObject.put("branch", head.get("hash"));
jsonObject.put("contents", operations);
jsonObject.put("signature", signedOpGroup.getSignature());
JSONArray payload = new JSONArray();
payload.put(jsonObject);
return nodeApplyOperation(payload);
}
private JSONObject runOperation(JSONObject head, JSONArray operations, String operationGroupHash,
String forgedOperationGroup, SignedOperationGroup signedOpGroup)
throws Exception
{
JSONObject jsonObject = new JSONObject();
String chainId = head.get("chain_id").toString();
jsonObject.put("branch", head.get("hash"));
jsonObject.put("contents", operations);
jsonObject.put("signature", signedOpGroup.getSignature());
JSONArray payload = new JSONArray();
payload.put(jsonObject);
return nodeRunOperation(payload, chainId);
}
private JSONObject checkAppliedOperationResults(JSONObject appliedOp) throws Exception
{
JSONObject returned = new JSONObject();
Boolean errors = false;
String reason = "";
String[] validAppliedKinds = new String[]
{ "activate_account", "reveal", "transaction", "origination", "delegation" };
String firstApplied = appliedOp.toString().replaceAll("\\\\n", "").replaceAll("\\\\", "");
JSONArray result = new JSONArray(new JSONObject(firstApplied).get("result").toString());
JSONObject first = (JSONObject) result.get(0);
if(isJSONObject(first.toString()))
{
// Check for error.
if(first.has("kind") && first.has("id"))
{
errors = true;
reason = "There were errors: kind '" + first.getString("kind") + "' id '" + first.getString("id") + "'";
}
}
else if(isJSONArray(first.toString()))
{
// Loop through contents and check for errors.
Integer elements = ((JSONArray) first.get("contents")).length();
String element = "";
for(Integer i = 0; i < elements; i++)
{
JSONObject operation_result = ((JSONObject) ((JSONObject) (((JSONObject) (((JSONArray) first
.get("contents")).get(i))).get("metadata"))).get("operation_result"));
element = ((JSONObject) operation_result).getString("status");
if(element.equals("failed") == true)
{
errors = true;
if(operation_result.has("errors"))
{
JSONObject err = (JSONObject) ((JSONArray) operation_result.get("errors")).get(0);
reason = "There were errors: kind '" + err.getString("kind") + "' id '" + err.getString("id") + "'";
}
break;
}
}
}
if(errors)
{
returned.put("result", reason);
}
else
{
returned.put("result", "");
}
return returned;
}
private JSONObject appendRevealOperation(JSONObject blockHead, EncKeys encKeys, String pkh, Integer counter)
throws Exception
{
// Create new JSON object for the reveal operation.
JSONObject revealOp = new JSONObject();
// Get public key from encKeys.
byte[] bytePk = encKeys.getEncPublicKey();
byte[] decPkBytes = decryptBytes(bytePk, TezosWallet.getEncryptionKey(encKeys));
StringBuilder builder2 = new StringBuilder();
for(byte decPkByte : decPkBytes)
{
builder2.append((char) (decPkByte));
}
String publicKey = builder2.toString();
// If Manager key is not revealed for account...
if(!isManagerKeyRevealedForAccount(blockHead, pkh))
{
BigDecimal fee = new BigDecimal("0.002490");
BigDecimal roundedFee = fee.setScale(6, BigDecimal.ROUND_HALF_UP);
revealOp.put("kind", "reveal");
revealOp.put("source", pkh);
revealOp.put("fee", (String.valueOf(roundedFee.multiply(BigDecimal.valueOf(UTEZ)).toBigInteger())));
revealOp.put("counter", String.valueOf(counter + 1));
revealOp.put("gas_limit", "15400");
revealOp.put("storage_limit", "300");
revealOp.put("public_key", publicKey);
}
else
{
revealOp = null;
}
return revealOp;
}
private boolean isManagerKeyRevealedForAccount(JSONObject blockHead, String pkh) throws Exception
{
Boolean result = false;
String blockHeadHash = blockHead.getString("hash");
String r = "";
Boolean hasResult = getAccountManagerForBlock(blockHeadHash, pkh).has("result");
if(hasResult)
{
r = (String) getAccountManagerForBlock(blockHeadHash, pkh).get("result");
// Do some cleaning.
r = r.replace("\"", "");
r = r.replace("\n", "");
r = r.trim();
if(r.equals("null") == true)
{
result = false;
}
else
{
// Account already revealed.
result = true;
}
}
return result;
}
private JSONObject injectOperation(SignedOperationGroup signedOpGroup) throws Exception
{
String payload = signedOpGroup.getSbytes();
return nodeInjectOperation("\"" + payload + "\"");
}
private JSONObject nodeInjectOperation(String payload) throws Exception
{
JSONObject result = (JSONObject) query("/injection/operation?chain=main", payload);
return result;
}
public JSONObject sign(byte[] bytes, EncKeys keys, String watermark) throws Exception
{
JSONObject response = new JSONObject();
// Access wallet keys to have authorization to perform the operation.
byte[] byteSk = keys.getEncPrivateKey();
byte[] decSkBytes = decryptBytes(byteSk, TezosWallet.getEncryptionKey(keys));
// First, we remove the edsk prefix from the decoded private key bytes.
byte[] edskPrefix =
{ (byte) 43, (byte) 246, (byte) 78, (byte) 7 };
byte[] decodedSk = Base58Check.decode(new String(decSkBytes));
byte[] privateKeyBytes = Arrays.copyOfRange(decodedSk, edskPrefix.length, decodedSk.length);
// Then we create a work array and check if the watermark parameter has been
// passed.
byte[] workBytes = ArrayUtils.addAll(bytes);
if(watermark != null)
{
byte[] wmBytes = HEX.decode(watermark);
workBytes = ArrayUtils.addAll(wmBytes, workBytes);
}
// Now we hash the combination of: watermark (if exists) + the bytes passed in
// parameters.
// The result will end up in the sig variable.
byte[] hashedWorkBytes = new byte[32];
int rc = sodium.crypto_generichash(hashedWorkBytes, hashedWorkBytes.length, workBytes, workBytes.length,
workBytes, 0);
byte[] sig = new byte[64];
int r = sodium.crypto_sign_detached(sig, null, hashedWorkBytes, hashedWorkBytes.length, privateKeyBytes);
// To create the edsig, we need to concatenate the edsig prefix with the sig and
// then encode it.
// The sbytes will be the concatenation of bytes (in hex) + sig (in hex).
byte[] edsigPrefix =
{ 9, (byte) 245, (byte) 205, (byte) 134, 18 };
byte[] edsigPrefixedSig = new byte[edsigPrefix.length + sig.length];
edsigPrefixedSig = ArrayUtils.addAll(edsigPrefix, sig);
String edsig = Base58Check.encode(edsigPrefixedSig);
String sbytes = HEX.encode(bytes) + HEX.encode(sig);
// Now, with all needed values ready, we create and deliver the response.
response.put("bytes", HEX.encode(bytes));
response.put("sig", HEX.encode(sig));
response.put("edsig", edsig);
response.put("sbytes", sbytes);
return response;
}
public JSONObject signWithLedger(byte[] bytes, String watermark) throws Exception
{
JSONObject response = new JSONObject();
String watermarkedForgedOperationBytesHex = "";
byte[] workBytes = ArrayUtils.addAll(bytes);
if(watermark != null)
{
byte[] wmBytes = HEX.decode(watermark);
workBytes = ArrayUtils.addAll(wmBytes, workBytes);
}
watermarkedForgedOperationBytesHex = HEX.encode(workBytes);
// There is a Ledger hardware wallet configured. Signing will be done with it.
Runtime rt = Runtime.getRuntime();
String[] commands = { Global.ledgerTezosFolderPath + Global.ledgerTezosFilePath, Global.ledgerDerivationPath, watermarkedForgedOperationBytesHex };
try
{
Process proc = rt.exec(commands);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
String s = "", signature="", error = "";
while ((s = stdInput.readLine()) != null)
{
signature=signature + s;
}
JSONObject jsonObject = new JSONObject(signature);
String ledgerSig = jsonObject.getString("signature");
String r = "";
while ((r = stdError.readLine()) != null)
{
error = error + r;
}
byte[] sig = new byte[64];
sig = HEX.decode(ledgerSig);
// To create the edsig, we need to concatenate the edsig prefix with the sig and
// then encode it.
byte[] edsigPrefix =
{ 9, (byte) 245, (byte) 205, (byte) 134, 18 };
byte[] edsigPrefixedSig = new byte[edsigPrefix.length + sig.length];
edsigPrefixedSig = ArrayUtils.addAll(edsigPrefix, sig);
String edsig = Base58Check.encode(edsigPrefixedSig);
// The sbytes will be the concatenation of bytes (in hex) + sig (in hex).
String sbytes = HEX.encode(bytes) + HEX.encode(sig);
// Now, with all needed values ready, we create and deliver the response.
response.put("bytes", HEX.encode(bytes));
response.put("sig", HEX.encode(sig));
response.put("edsig", edsig);
response.put("sbytes", sbytes);
}
catch(Exception e)
{
response = null;
}
return response;
}
// Tests if a string is a valid JSON.
private Boolean isJSONObject(String myStr)
{
try
{
JSONObject testJSON = new JSONObject(myStr);
return testJSON != null;
} catch (JSONException e)
{
return false;
}
}
// Tests if s string is a valid JSON Array.
private Boolean isJSONArray(String myStr)
{
try
{
JSONArray testJSONArray = new JSONArray(myStr);
return testJSONArray != null;
} catch (JSONException e)
{
return false;
}
}
// Decryption routine.
private static byte[] decryptBytes(byte[] encrypted, byte[] key)
{
try
{
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec);
return cipher.doFinal(encrypted);
} catch (Exception e)
{
e.printStackTrace();
}
return null;
}
public JSONObject sendDelegationOperation(String delegator, String delegate, BigDecimal fee, String gasLimit,
String storageLimit, EncKeys encKeys)
throws Exception
{
JSONObject result = new JSONObject();
BigDecimal roundedFee = fee.setScale(6, BigDecimal.ROUND_HALF_UP);
JSONArray operations = new JSONArray();
JSONObject revealOperation = new JSONObject();
JSONObject transaction = new JSONObject();
JSONObject head = new JSONObject();
JSONObject account = new JSONObject();
Integer counter = 0;
if(gasLimit == null)
{
gasLimit = "10100";
}
else
{
if((gasLimit.length() == 0) || (gasLimit.equals("0")))
{
gasLimit = "10100";
}
}
if(storageLimit == null)
{
storageLimit = "0";
}
else
{
if(storageLimit.length() == 0)
{
storageLimit = "0";
}
}