/
ImmuClient.java
1171 lines (918 loc) · 40.3 KB
/
ImmuClient.java
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
/*
Copyright 2022 CodeNotary, Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.codenotary.immudb4j;
import com.google.protobuf.ByteString;
import com.google.protobuf.Empty;
import io.codenotary.immudb.ImmuServiceGrpc;
import io.codenotary.immudb.ImmudbProto;
import io.codenotary.immudb.ImmudbProto.ScanRequest;
import io.codenotary.immudb4j.crypto.CryptoUtils;
import io.codenotary.immudb4j.crypto.DualProof;
import io.codenotary.immudb4j.crypto.InclusionProof;
import io.codenotary.immudb4j.exceptions.*;
import io.codenotary.immudb4j.user.Permission;
import io.codenotary.immudb4j.user.User;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.Metadata;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.MetadataUtils;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* The official immudb Java Client.
*
* @author Jeronimo Irazabal
* @author Marius Ileana
*/
public class ImmuClient {
private static final String AUTH_HEADER = "authorization";
private final ImmuServiceGrpc.ImmuServiceBlockingStub stub;
private final boolean withAuth;
private final ImmuStateHolder stateHolder;
private ManagedChannel channel;
private String authToken;
private String currentServerUuid;
private String currentDb = "defaultdb";
private final PublicKey serverSigningKey;
public ImmuClient(Builder builder) {
this.stub = createStubFrom(builder);
this.withAuth = builder.isWithAuth();
this.stateHolder = builder.getStateHolder();
this.serverSigningKey = builder.getServerSigningKey();
}
public static Builder newBuilder() {
return new Builder();
}
private ImmuServiceGrpc.ImmuServiceBlockingStub createStubFrom(Builder builder) {
channel = ManagedChannelBuilder.forAddress(builder.getServerUrl(), builder.getServerPort())
.usePlaintext()
.intercept(new ImmuServerUUIDInterceptor(this))
.build();
return ImmuServiceGrpc.newBlockingStub(channel);
}
// ---------------------------------------------------------------------
// These two currentServerUuid related methods are not publicly exposed,
// since these should be called by the ImmuServerUUIDInterceptor only.
void setCurrentServerUuid(String serverUuid) {
currentServerUuid = serverUuid;
}
String getCurrentServerUuid() {
return currentServerUuid;
}
// ---------------------------------------------------------------------
public synchronized void shutdown() {
if (channel == null) {
return;
}
channel.shutdown();
if (!channel.isShutdown()) {
try {
channel.awaitTermination(2, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// nothing to do here.
}
}
channel = null;
}
public synchronized boolean isShutdown() {
return channel == null;
}
private ImmuServiceGrpc.ImmuServiceBlockingStub getStub() {
if (!withAuth || authToken == null) {
return stub;
}
Metadata metadata = new Metadata();
metadata.put(Metadata.Key.of(AUTH_HEADER, Metadata.ASCII_STRING_MARSHALLER), "Bearer " + authToken);
return MetadataUtils.attachHeaders(stub, metadata);
}
public synchronized void login(String username, String password) {
ImmudbProto.LoginRequest loginRequest = ImmudbProto.LoginRequest
.newBuilder()
.setUser(Utils.toByteString(username))
.setPassword(Utils.toByteString(password))
.build();
ImmudbProto.LoginResponse loginResponse = getStub().login(loginRequest);
authToken = loginResponse.getToken();
}
public synchronized void logout() {
getStub().logout(com.google.protobuf.Empty.getDefaultInstance());
authToken = null;
}
/**
* Get the locally saved state of the current database.
* If nothing exists already, it is fetched from the server and save it locally.
*/
public ImmuState state() {
ImmuState state = stateHolder.getState(currentServerUuid, currentDb);
if (state == null) {
state = currentState();
stateHolder.setState(currentServerUuid, state);
}
return state;
}
/**
* Get the current database state that exists on the server.
* It may throw a RuntimeException if server's state signature verification fails
* (if this feature is enabled on the client side, at least).
*/
public ImmuState currentState() {
final Empty empty = com.google.protobuf.Empty.getDefaultInstance();
final ImmudbProto.ImmutableState state = getStub().currentState(empty);
final ImmuState immuState = ImmuState.valueOf(state);
if (!immuState.checkSignature(serverSigningKey)) {
throw new RuntimeException("State signature verification failed");
}
return immuState;
}
//
// ========== DATABASE ==========
//
public void createDatabase(String database) {
final ImmudbProto.CreateDatabaseRequest db = ImmudbProto.CreateDatabaseRequest.newBuilder()
.setName(database)
.build();
getStub().createDatabaseV2(db);
}
public synchronized void useDatabase(String database) {
final ImmudbProto.Database db = ImmudbProto.Database.newBuilder()
.setDatabaseName(database)
.build();
final ImmudbProto.UseDatabaseReply response = getStub().useDatabase(db);
authToken = response.getToken();
currentDb = database;
}
public List<String> databases() {
final ImmudbProto.DatabaseListRequestV2 req = ImmudbProto.DatabaseListRequestV2.newBuilder().build();
final ImmudbProto.DatabaseListResponseV2 res = getStub().databaseListV2(req);
final List<String> list = new ArrayList<>(res.getDatabasesCount());
for (ImmudbProto.DatabaseWithSettings db : res.getDatabasesList()) {
list.add(db.getName());
}
return list;
}
//
// ========== GET ==========
//
public Entry get(String key) throws KeyNotFoundException {
return get(Utils.toByteArray(key));
}
public Entry get(byte[] key) throws KeyNotFoundException {
return getAtTx(key, 0);
}
public Entry getAtTx(String key, long tx) throws KeyNotFoundException {
return getAtTx(Utils.toByteArray(key), tx);
}
public Entry getAtTx(byte[] key, long tx) throws KeyNotFoundException {
final ImmudbProto.KeyRequest req =ImmudbProto.KeyRequest.newBuilder()
.setKey(Utils.toByteString(key))
.setAtTx(tx)
.build();
try {
return Entry.valueOf(getStub().get(req));
} catch (StatusRuntimeException e) {
if (e.getMessage().contains("key not found")) {
throw new KeyNotFoundException();
}
throw e;
}
}
public Entry getSinceTx(String key, long tx) throws KeyNotFoundException {
return getSinceTx(Utils.toByteArray(key), tx);
}
public Entry getSinceTx(byte[] key, long tx) throws KeyNotFoundException {
final ImmudbProto.KeyRequest req =ImmudbProto.KeyRequest.newBuilder()
.setKey(Utils.toByteString(key))
.setSinceTx(tx)
.build();
try {
return Entry.valueOf(getStub().get(req));
} catch (StatusRuntimeException e) {
if (e.getMessage().contains("key not found")) {
throw new KeyNotFoundException();
}
throw e;
}
}
public Entry getAtRevision(String key, long rev) throws KeyNotFoundException {
return getAtRevision(Utils.toByteArray(key), rev);
}
public Entry getAtRevision(byte[] key, long rev) throws KeyNotFoundException {
final ImmudbProto.KeyRequest req =ImmudbProto.KeyRequest.newBuilder()
.setKey(Utils.toByteString(key))
.setAtRevision(rev)
.build();
try {
return Entry.valueOf(getStub().get(req));
} catch (StatusRuntimeException e) {
if (e.getMessage().contains("key not found")) {
throw new KeyNotFoundException();
}
throw e;
}
}
public List<Entry> getAll(List<String> keys) {
final List<ByteString> keysBS = new ArrayList<>(keys.size());
for (String key : keys) {
keysBS.add(Utils.toByteString(key));
}
final ImmudbProto.KeyListRequest req = ImmudbProto.KeyListRequest.newBuilder().addAllKeys(keysBS).build();
final ImmudbProto.Entries entries = getStub().getAll(req);
final List<Entry> result = new ArrayList<>(entries.getEntriesCount());
for (ImmudbProto.Entry entry : entries.getEntriesList()) {
result.add(Entry.valueOf(entry));
}
return result;
}
public Entry verifiedGet(String key) throws KeyNotFoundException, VerificationException {
return verifiedGetAtTx(key, 0);
}
public Entry verifiedGet(byte[] key) throws KeyNotFoundException, VerificationException {
return verifiedGetAtTx(key, 0);
}
public Entry verifiedGetAtTx(String key, long tx) throws KeyNotFoundException, VerificationException {
return verifiedGetAtTx(Utils.toByteArray(key), tx);
}
public Entry verifiedGetAtTx(byte[] key, long tx) throws KeyNotFoundException, VerificationException {
final ImmudbProto.KeyRequest keyReq = ImmudbProto.KeyRequest.newBuilder()
.setKey(Utils.toByteString(key))
.setAtTx(tx)
.build();
return verifiedGet(keyReq, state());
}
public Entry verifiedGetSinceTx(String key, long tx) throws KeyNotFoundException, VerificationException {
return verifiedGetSinceTx(Utils.toByteArray(key), tx);
}
public Entry verifiedGetSinceTx(byte[] key, long tx) throws KeyNotFoundException, VerificationException {
final ImmudbProto.KeyRequest keyReq = ImmudbProto.KeyRequest.newBuilder()
.setKey(Utils.toByteString(key))
.setSinceTx(tx)
.build();
return verifiedGet(keyReq, state());
}
public Entry verifiedGetAtRevision(String key, long rev) throws KeyNotFoundException, VerificationException {
return verifiedGetAtRevision(Utils.toByteArray(key), rev);
}
public Entry verifiedGetAtRevision(byte[] key, long rev) throws KeyNotFoundException, VerificationException {
final ImmudbProto.KeyRequest keyReq = ImmudbProto.KeyRequest.newBuilder()
.setKey(Utils.toByteString(key))
.setAtRevision(rev)
.build();
return verifiedGet(keyReq, state());
}
private Entry verifiedGet(ImmudbProto.KeyRequest keyReq, ImmuState state) throws KeyNotFoundException, VerificationException {
final ImmudbProto.VerifiableGetRequest vGetReq = ImmudbProto.VerifiableGetRequest.newBuilder()
.setKeyRequest(keyReq)
.setProveSinceTx(state.txId)
.build();
final ImmudbProto.VerifiableEntry vEntry = getStub().verifiableGet(vGetReq);
final InclusionProof inclusionProof = InclusionProof.valueOf(vEntry.getInclusionProof());
final DualProof dualProof = DualProof.valueOf(vEntry.getVerifiableTx().getDualProof());
byte[] eh;
long sourceId, targetId;
byte[] sourceAlh;
byte[] targetAlh;
final Entry entry = Entry.valueOf(vEntry.getEntry());
if (entry.getReferenceBy() == null && !Arrays.equals(keyReq.getKey().toByteArray(), entry.getKey())) {
throw new RuntimeException("Data is corrupted: entry does not belong to specified key");
}
if (entry.getReferenceBy() != null && !Arrays.equals(keyReq.getKey().toByteArray(), entry.getReferenceBy().getKey())) {
throw new RuntimeException("Data is corrupted: entry does not belong to specified key");
}
if (entry.getMetadata() != null && entry.getMetadata().deleted()) {
throw new RuntimeException("Data is corrupted: entry is marked as deleted");
}
if (keyReq.getAtTx() != 0 && entry.getTx() != keyReq.getAtTx()) {
throw new RuntimeException("Data is corrupted: entry does not belong to specified tx");
}
if (state.txId <= entry.getTx()) {
final byte[] digest = vEntry.getVerifiableTx().getDualProof().getTargetTxHeader().getEH().toByteArray();
eh = CryptoUtils.digestFrom(digest);
sourceId = state.txId;
sourceAlh = CryptoUtils.digestFrom(state.txHash);
targetId = entry.getTx();
targetAlh = dualProof.targetTxHeader.alh();
} else {
final byte[] digest = vEntry.getVerifiableTx().getDualProof().getSourceTxHeader().getEH().toByteArray();
eh = CryptoUtils.digestFrom(digest);
sourceId = entry.getTx();
sourceAlh = dualProof.sourceTxHeader.alh();
targetId = state.txId;
targetAlh = CryptoUtils.digestFrom(state.txHash);
}
final byte[] kvDigest = entry.digestFor(vEntry.getVerifiableTx().getTx().getHeader().getVersion());
if (!CryptoUtils.verifyInclusion(inclusionProof, kvDigest, eh)) {
throw new VerificationException("Inclusion verification failed.");
}
if (state.txId > 0) {
if (!CryptoUtils.verifyDualProof(
dualProof,
sourceId,
targetId,
sourceAlh,
targetAlh
)) {
throw new VerificationException("Dual proof verification failed.");
}
}
final ImmuState newState = new ImmuState(
currentDb,
targetId,
targetAlh,
vEntry.getVerifiableTx().getSignature().toByteArray());
if (!newState.checkSignature(serverSigningKey)) {
throw new RuntimeException("State signature verification failed");
}
stateHolder.setState(currentServerUuid, newState);
return Entry.valueOf(vEntry.getEntry());
}
//
// ========== DELETE ==========
//
public TxHeader delete(String key) throws KeyNotFoundException {
return delete(Utils.toByteArray(key));
}
public TxHeader delete(byte[] key) throws KeyNotFoundException {
try {
final ImmudbProto.DeleteKeysRequest req = ImmudbProto.DeleteKeysRequest.newBuilder()
.addKeys(Utils.toByteString(key))
.build();
return TxHeader.valueOf(getStub().delete(req));
} catch (StatusRuntimeException e) {
if (e.getMessage().contains("key not found")) {
throw new KeyNotFoundException();
}
throw e;
}
}
//
// ========== HISTORY ==========
//
public List<Entry> history(String key, int limit, long offset, boolean desc) throws KeyNotFoundException {
return history(Utils.toByteArray(key), limit, offset, desc);
}
public List<Entry> history(byte[] key, int limit, long offset, boolean desc) throws KeyNotFoundException {
try {
ImmudbProto.Entries entries = getStub().history(ImmudbProto.HistoryRequest.newBuilder()
.setKey(Utils.toByteString(key))
.setLimit(limit)
.setOffset(offset)
.setDesc(desc)
.build()
);
return buildList(entries);
} catch (StatusRuntimeException e) {
if (e.getMessage().contains("key not found")) {
throw new KeyNotFoundException();
}
throw e;
}
}
//
// ========== SCAN ==========
//
public List<Entry> scan(String prefix) {
return scan(Utils.toByteArray(prefix));
}
public List<Entry> scan(byte[] prefix) {
return scan(prefix, 0, false);
}
public List<Entry> scan(String prefix, long limit, boolean desc) {
return scan(Utils.toByteArray(prefix), limit, desc);
}
public List<Entry> scan(byte[] prefix, long limit, boolean desc) {
return scan(prefix, null, limit, desc);
}
public List<Entry> scan(String prefix, String seekKey, long limit, boolean desc) {
return scan(Utils.toByteArray(prefix), Utils.toByteArray(seekKey), limit, desc);
}
public List<Entry> scan(String prefix, String seekKey, String endKey, long limit, boolean desc) {
return scan(Utils.toByteArray(prefix), Utils.toByteArray(seekKey), Utils.toByteArray(endKey), limit, desc);
}
public List<Entry> scan(byte[] prefix, byte[] seekKey, long limit, boolean desc) {
return scan(prefix, seekKey, null, limit, desc);
}
public List<Entry> scan(byte[] prefix, byte[] seekKey, byte[] endKey, long limit, boolean desc) {
return scan(prefix, seekKey, endKey, false, false, limit, desc);
}
public List<Entry> scan(byte[] prefix, byte[] seekKey, byte[] endKey, boolean inclusiveSeek, boolean inclusiveEnd,
long limit, boolean desc) {
final ImmudbProto.ScanRequest req = ScanRequest.newBuilder()
.setPrefix(Utils.toByteString(prefix))
.setSeekKey(Utils.toByteString(seekKey))
.setEndKey(Utils.toByteString(endKey))
.setInclusiveSeek(inclusiveSeek)
.setInclusiveEnd(inclusiveEnd)
.setLimit(limit)
.setDesc(desc)
.build();
final ImmudbProto.Entries entries = getStub().scan(req);
return buildList(entries);
}
//
// ========== SET ==========
//
public TxHeader set(String key, byte[] value) throws CorruptedDataException {
return set(Utils.toByteArray(key), value);
}
public TxHeader set(byte[] key, byte[] value) throws CorruptedDataException {
final ImmudbProto.KeyValue kv = ImmudbProto.KeyValue.newBuilder()
.setKey(Utils.toByteString(key))
.setValue(Utils.toByteString(value))
.build();
final ImmudbProto.SetRequest req = ImmudbProto.SetRequest.newBuilder().addKVs(kv).build();
final ImmudbProto.TxHeader txHdr = getStub().set(req);
if (txHdr.getNentries() != 1) {
throw new CorruptedDataException();
}
return TxHeader.valueOf(txHdr);
}
public TxHeader setAll(List<KVPair> kvList) throws CorruptedDataException {
final ImmudbProto.SetRequest.Builder reqBuilder = ImmudbProto.SetRequest.newBuilder();
for (KVPair kv : kvList) {
ImmudbProto.KeyValue.Builder kvBuilder = ImmudbProto.KeyValue.newBuilder();
kvBuilder.setKey(Utils.toByteString(kv.getKey()));
kvBuilder.setValue(Utils.toByteString(kv.getValue()));
reqBuilder.addKVs(kvBuilder.build());
}
final ImmudbProto.TxHeader txHdr = getStub().set(reqBuilder.build());
if (txHdr.getNentries() != kvList.size()) {
throw new CorruptedDataException();
}
return TxHeader.valueOf(txHdr);
}
public TxHeader setReference(String key, String referencedKey) throws CorruptedDataException {
return setReference(Utils.toByteArray(key), Utils.toByteArray(referencedKey));
}
public TxHeader setReference(byte[] key, byte[] referencedKey) throws CorruptedDataException {
return setReference(key, referencedKey, 0);
}
public TxHeader setReference(String key, String referencedKey, long atTx) throws CorruptedDataException {
return setReference(Utils.toByteArray(key), Utils.toByteArray(referencedKey), atTx);
}
public TxHeader setReference(byte[] key, byte[] referencedKey, long atTx) throws CorruptedDataException {
final ImmudbProto.ReferenceRequest req = ImmudbProto.ReferenceRequest.newBuilder()
.setKey(Utils.toByteString(key))
.setReferencedKey(Utils.toByteString(referencedKey))
.setAtTx(atTx)
.setBoundRef(atTx > 0)
.build();
final ImmudbProto.TxHeader txHdr = getStub().setReference(req);
if (txHdr.getNentries() != 1) {
throw new CorruptedDataException();
}
return TxHeader.valueOf(txHdr);
}
public TxHeader verifiedSet(String key, byte[] value) throws VerificationException {
return verifiedSet(Utils.toByteArray(key), value);
}
public TxHeader verifiedSet(byte[] key, byte[] value) throws VerificationException {
final ImmuState state = state();
final ImmudbProto.KeyValue kv = ImmudbProto.KeyValue.newBuilder()
.setKey(Utils.toByteString(key))
.setValue(Utils.toByteString(value))
.build();
final ImmudbProto.VerifiableSetRequest vSetReq = ImmudbProto.VerifiableSetRequest.newBuilder()
.setSetRequest(ImmudbProto.SetRequest.newBuilder().addKVs(kv).build())
.setProveSinceTx(state.txId)
.build();
final ImmudbProto.VerifiableTx vtx = getStub().verifiableSet(vSetReq);
final int ne = vtx.getTx().getHeader().getNentries();
if (ne != 1 || vtx.getTx().getEntriesList().size() != 1) {
throw new VerificationException(
String.format("Got back %d entries (in tx metadata) instead of 1.", ne)
);
}
final Tx tx;
try {
tx = Tx.valueOf(vtx.getTx());
} catch (Exception e) {
throw new VerificationException("Failed to extract the transaction.", e);
}
final TxHeader txHeader = tx.getHeader();
final Entry entry = Entry.valueOf(ImmudbProto.Entry.newBuilder()
.setKey(Utils.toByteString(key))
.setValue(Utils.toByteString(value))
.build()
);
final InclusionProof inclusionProof = tx.proof(entry.getEncodedKey());
if (!CryptoUtils.verifyInclusion(inclusionProof, entry.digestFor(txHeader.getVersion()), txHeader.getEh())) {
throw new VerificationException("Data is corrupted (verify inclusion failed)");
}
final ImmuState newState = verifyDualProof(vtx, tx, state);
if (!newState.checkSignature(serverSigningKey)) {
throw new RuntimeException("State signature verification failed");
}
stateHolder.setState(currentServerUuid, newState);
return TxHeader.valueOf(vtx.getTx().getHeader());
}
public TxHeader verifiedSetReference(byte[] key, byte[] referencedKey) throws VerificationException {
return verifiedSetReference(key, referencedKey, 0);
}
public TxHeader verifiedSetReference(byte[] key, byte[] referencedKey, long atTx) throws VerificationException {
final ImmuState state = state();
final ImmudbProto.ReferenceRequest refReq = ImmudbProto.ReferenceRequest.newBuilder()
.setKey(Utils.toByteString(key))
.setReferencedKey(Utils.toByteString(referencedKey))
.setAtTx(atTx)
.setBoundRef(atTx > 0)
.build();
final ImmudbProto.VerifiableReferenceRequest vRefReq = ImmudbProto.VerifiableReferenceRequest.newBuilder()
.setReferenceRequest(refReq)
.setProveSinceTx(state.txId)
.build();
final ImmudbProto.VerifiableTx vtx = getStub().verifiableSetReference(vRefReq);
final int vtxNentries = vtx.getTx().getHeader().getNentries();
if (vtxNentries != 1) {
throw new VerificationException(String.format("Data is corrupted (verifTx has %d Nentries instead of 1).",
vtxNentries));
}
final Tx tx;
try {
tx = Tx.valueOf(vtx.getTx());
} catch (Exception e) {
throw new VerificationException("Failed to extract the transaction.", e);
}
final TxHeader txHeader = tx.getHeader();
final Entry entry = Entry.valueOf(ImmudbProto.Entry.newBuilder()
.setKey(Utils.toByteString(referencedKey))
.setReferencedBy(ImmudbProto.Reference.newBuilder()
.setKey(Utils.toByteString(key))
.setAtTx(atTx)
.build()
)
.build()
);
final InclusionProof inclusionProof = tx.proof(entry.getEncodedKey());
if (!CryptoUtils.verifyInclusion(inclusionProof, entry.digestFor(txHeader.getVersion()), txHeader.getEh())) {
throw new VerificationException("Data is corrupted (inclusion verification failed).");
}
if (Arrays.equals(txHeader.getEh(), CryptoUtils.digestFrom(vtx.getDualProof().getTargetTxHeader().getEH().toByteArray()))) {
throw new VerificationException("Data is corrupted (different digests).");
}
final ImmuState newState = verifyDualProof(vtx, tx, state);
if (!newState.checkSignature(serverSigningKey)) {
throw new RuntimeException("State signature verification failed");
}
stateHolder.setState(currentServerUuid, newState);
return TxHeader.valueOf(vtx.getTx().getHeader());
}
private ImmuState verifyDualProof(ImmudbProto.VerifiableTx vtx, Tx tx, ImmuState state)
throws VerificationException {
final long sourceId = state.txId;
final long targetId = tx.getHeader().getId();
final byte[] sourceAlh = CryptoUtils.digestFrom(state.txHash);
final byte[] targetAlh = tx.getHeader().alh();
if (state.txId > 0) {
if (!CryptoUtils.verifyDualProof(
DualProof.valueOf(vtx.getDualProof()),
sourceId,
targetId,
sourceAlh,
targetAlh
)) {
throw new VerificationException("Data is corrupted (dual proof verification failed).");
}
}
return new ImmuState(currentDb, targetId, targetAlh, vtx.getSignature().getSignature().toByteArray());
}
//
// ========== Z ==========
//
public TxHeader zAdd(String set, String key, double score) throws CorruptedDataException {
return zAdd(Utils.toByteArray(set), Utils.toByteArray(key), score);
}
public TxHeader zAdd(byte[] set, byte[] key, double score) throws CorruptedDataException {
return zAdd(set, key, 0, score);
}
public TxHeader zAdd(byte[] set, byte[] key, long atTx, double score) throws CorruptedDataException {
final ImmudbProto.TxHeader txHdr = getStub().zAdd(
ImmudbProto.ZAddRequest.newBuilder()
.setSet(Utils.toByteString(set))
.setKey(Utils.toByteString(key))
.setAtTx(atTx)
.setScore(score)
.setBoundRef(atTx > 0)
.build()
);
if (txHdr.getNentries() != 1) {
throw new CorruptedDataException();
}
return TxHeader.valueOf(txHdr);
}
public TxHeader verifiedZAdd(String set, String key, double score) throws VerificationException {
return verifiedZAdd(Utils.toByteArray(set), Utils.toByteArray(key), score);
}
public TxHeader verifiedZAdd(byte[] set, byte[] key, double score) throws VerificationException {
return verifiedZAdd(set, key,0, score);
}
public TxHeader verifiedZAdd(String set, String key, long atTx, double score) throws VerificationException {
return verifiedZAdd(Utils.toByteArray(set), Utils.toByteArray(key), atTx, score);
}
public TxHeader verifiedZAdd(byte[] set, byte[] key, long atTx, double score) throws VerificationException {
final ImmuState state = state();
final ImmudbProto.ZAddRequest zAddReq = ImmudbProto.ZAddRequest.newBuilder()
.setSet(Utils.toByteString(set))
.setKey(Utils.toByteString(key))
.setAtTx(atTx)
.setBoundRef(atTx > 0)
.setScore(score)
.build();
final ImmudbProto.VerifiableZAddRequest vZAddReq = ImmudbProto.VerifiableZAddRequest.newBuilder()
.setZAddRequest(zAddReq)
.setProveSinceTx(state.txId)
.build();
final ImmudbProto.VerifiableTx vtx = getStub().verifiableZAdd(vZAddReq);
if (vtx.getTx().getHeader().getNentries() != 1) {
throw new VerificationException("Data is corrupted.");
}
final Tx tx;
try {
tx = Tx.valueOf(vtx.getTx());
} catch (Exception e) {
throw new VerificationException("Failed to extract the transaction.", e);
}
final TxHeader txHeader = tx.getHeader();
final ZEntry entry = ZEntry.valueOf(ImmudbProto.ZEntry.newBuilder()
.setSet(Utils.toByteString(set))
.setKey(Utils.toByteString(key))
.setAtTx(atTx)
.setScore(score)
.build()
);
InclusionProof inclusionProof = tx.proof(entry.getEncodedKey());
if (!CryptoUtils.verifyInclusion(inclusionProof, entry.digestFor(txHeader.getVersion()), txHeader.getEh())) {
throw new VerificationException("Data is corrupted (inclusion verification failed).");
}
if (!Arrays.equals(txHeader.getEh(), CryptoUtils.digestFrom(vtx.getDualProof().getTargetTxHeader().getEH().toByteArray()))) {
throw new VerificationException("Data is corrupted (different digests).");
}
final ImmuState newState = verifyDualProof(vtx, tx, state);
if (!newState.checkSignature(serverSigningKey)) {
throw new RuntimeException("State signature verification failed");
}
stateHolder.setState(currentServerUuid, newState);
return TxHeader.valueOf(vtx.getTx().getHeader());
}
public List<ZEntry> zScan(String set, long limit, boolean reverse) {
return zScan(Utils.toByteArray(set), limit, reverse);
}
public List<ZEntry> zScan(byte[] set, long limit, boolean reverse) {
final ImmudbProto.ZScanRequest req = ImmudbProto.ZScanRequest
.newBuilder()
.setSet(Utils.toByteString(set))
.setLimit(limit)
.setDesc(reverse)
.build();
final ImmudbProto.ZEntries zEntries = getStub().zScan(req);
return buildList(zEntries);
}
//
// ========== TX ==========
//
public Tx txById(long txId) throws TxNotFoundException, NoSuchAlgorithmException {
try {
final ImmudbProto.Tx tx = getStub().txById(ImmudbProto.TxRequest.newBuilder().setTx(txId).build());
return Tx.valueOf(tx);
} catch (StatusRuntimeException e) {
if (e.getMessage().contains("tx not found")) {
throw new TxNotFoundException();
}
throw e;
}
}
public Tx verifiedTxById(long txId) throws TxNotFoundException, VerificationException {
final ImmuState state = state();
final ImmudbProto.VerifiableTxRequest vTxReq = ImmudbProto.VerifiableTxRequest.newBuilder()
.setTx(txId)
.setProveSinceTx(state.txId)
.build();
final ImmudbProto.VerifiableTx vtx;
try {
vtx = getStub().verifiableTxById(vTxReq);
} catch (StatusRuntimeException e) {
if (e.getMessage().contains("tx not found")) {
throw new TxNotFoundException();
}
throw e;
}
final DualProof dualProof = DualProof.valueOf(vtx.getDualProof());
long sourceId;
long targetId;
byte[] sourceAlh;
byte[] targetAlh;
if (state.txId <= txId) {
sourceId = state.txId;
sourceAlh = CryptoUtils.digestFrom(state.txHash);
targetId = txId;
targetAlh = dualProof.targetTxHeader.alh();
} else {
sourceId = txId;
sourceAlh = dualProof.sourceTxHeader.alh();
targetId = state.txId;
targetAlh = CryptoUtils.digestFrom(state.txHash);
}
if (state.txId > 0) {
if (!CryptoUtils.verifyDualProof(
DualProof.valueOf(vtx.getDualProof()),
sourceId,
targetId,
sourceAlh,
targetAlh
)) {
throw new VerificationException("Data is corrupted (dual proof verification failed).");
}
}
final Tx tx;
try {
tx = Tx.valueOf(vtx.getTx());
} catch (Exception e) {
throw new VerificationException("Failed to extract the transaction.", e);
}
final ImmuState newState = new ImmuState(currentDb, targetId, targetAlh, vtx.getSignature().getSignature().toByteArray());
if (!newState.checkSignature(serverSigningKey)) {
throw new RuntimeException("State signature verification failed");
}
stateHolder.setState(currentServerUuid, newState);
return tx;
}
public List<Tx> txScan(long initialTxId) {
final ImmudbProto.TxScanRequest req = ImmudbProto.TxScanRequest.newBuilder().setInitialTx(initialTxId).build();
final ImmudbProto.TxList txList = getStub().txScan(req);
return buildList(txList);
}
public List<Tx> txScan(long initialTxId, int limit, boolean desc) {
final ImmudbProto.TxScanRequest req = ImmudbProto.TxScanRequest
.newBuilder()
.setInitialTx(initialTxId)
.setLimit(limit)
.setDesc(desc)
.build();
final ImmudbProto.TxList txList = getStub().txScan(req);
return buildList(txList);
}
//
// ========== HEALTH ==========
//
public boolean healthCheck() {
return getStub().health(Empty.getDefaultInstance()).getStatus();
}
public boolean isConnected() {
return channel != null;
}
//
// ========== USER MGMT ==========
//
public List<User> listUsers() {