/
ImmuClient.java
1815 lines (1401 loc) · 61.1 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.Chunk;
import io.codenotary.immudb.ImmudbProto.NamedParam;
import io.codenotary.immudb.ImmudbProto.NewTxResponse;
import io.codenotary.immudb.ImmudbProto.ScanRequest;
import io.codenotary.immudb.ImmudbProto.Score;
import io.codenotary.immudb.ImmudbProto.TxMode;
import io.codenotary.immudb4j.basics.LatchHolder;
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.sql.SQLException;
import io.codenotary.immudb4j.sql.SQLQueryResult;
import io.codenotary.immudb4j.sql.SQLValue;
import io.codenotary.immudb4j.user.Permission;
import io.codenotary.immudb4j.user.User;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import io.grpc.ConnectivityState;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
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 final PublicKey serverSigningKey;
private final ImmuStateHolder stateHolder;
private long keepAlivePeriod;
private int chunkSize;
private ManagedChannel channel;
private final ImmuServiceGrpc.ImmuServiceBlockingStub blockingStub;
private final ImmuServiceGrpc.ImmuServiceStub nonBlockingStub;
private Session session;
private Timer sessionHeartBeat;
public ImmuClient(Builder builder) {
stateHolder = builder.getStateHolder();
serverSigningKey = builder.getServerSigningKey();
keepAlivePeriod = builder.getKeepAlivePeriod();
chunkSize = builder.getChunkSize();
channel = ManagedChannelBuilder
.forAddress(builder.getServerUrl(), builder.getServerPort())
.usePlaintext()
.intercept(new ImmudbAuthRequestInterceptor(this))
.build();
blockingStub = ImmuServiceGrpc.newBlockingStub(channel);
nonBlockingStub = ImmuServiceGrpc.newStub(channel);
}
public static Builder newBuilder() {
return new Builder();
}
public synchronized void shutdown() throws InterruptedException {
if (channel == null) {
return;
}
if (session != null) {
closeSession();
}
try {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
} finally {
channel = null;
}
}
protected synchronized Session getSession() {
return session;
}
public synchronized void openSession(String database, String username, String password) {
if (session != null) {
throw new IllegalStateException("session already opened");
}
final ImmudbProto.OpenSessionRequest req = ImmudbProto.OpenSessionRequest
.newBuilder()
.setDatabaseName(database)
.setUsername(Utils.toByteString(username))
.setPassword(Utils.toByteString(password))
.build();
final ImmudbProto.OpenSessionResponse resp = this.blockingStub.openSession(req);
session = new Session(resp.getSessionID(), database);
sessionHeartBeat = new Timer();
sessionHeartBeat.schedule(new TimerTask() {
@Override
public void run() {
try {
synchronized (ImmuClient.this) {
if (session != null) {
blockingStub.keepAlive(Empty.getDefaultInstance());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, 0, keepAlivePeriod);
}
public synchronized void closeSession() {
if (session == null) {
throw new IllegalStateException("no open session");
}
sessionHeartBeat.cancel();
try {
blockingStub.closeSession(Empty.getDefaultInstance());
} finally {
session = null;
}
}
/**
* Get the locally saved state of the current database.
* If nothing exists already, it is fetched from the server and save it locally.
*/
private ImmuState state() throws VerificationException {
if (session == null) {
throw new IllegalStateException("no open session");
}
ImmuState state = stateHolder.getState(session.getDatabase());
if (state == null) {
state = currentState();
stateHolder.setState(state);
}
return state;
}
/**
* Get the current database state that exists on the server.
* It may throw VerificationException if server's state signature verification
* fails
* (if this feature is enabled on the client side, at least).
* Note: local state is not updated because this is not a verified operation
*/
public synchronized ImmuState currentState() throws VerificationException {
if (session == null) {
throw new IllegalStateException("no open session");
}
final ImmudbProto.ImmutableState state = blockingStub.currentState(Empty.getDefaultInstance());
final ImmuState immuState = ImmuState.valueOf(state);
if (!session.getDatabase().equals(immuState.getDatabase())) {
throw new VerificationException("database mismatch");
}
if (!immuState.checkSignature(serverSigningKey)) {
throw new VerificationException("State signature verification failed");
}
return immuState;
}
//
// ========== SQL ==========
//
public synchronized void beginTransaction() throws SQLException {
if (session == null) {
throw new IllegalStateException("no open session");
}
if (session.getTransactionID() != null) {
throw new IllegalStateException("transaction already initiated");
}
final ImmudbProto.NewTxRequest req = ImmudbProto.NewTxRequest.newBuilder()
.setMode(TxMode.ReadWrite)
.build();
final NewTxResponse res = blockingStub.newTx(req);
session.setTransactionID(res.getTransactionID());
}
public synchronized void commitTransaction() throws SQLException {
if (session == null) {
throw new IllegalStateException("no open session");
}
if (session.getTransactionID() == null) {
throw new IllegalStateException("no transaction initiated");
}
blockingStub.commit(Empty.getDefaultInstance());
session.setTransactionID( null);
}
public synchronized void rollbackTransaction() throws SQLException {
if (session == null) {
throw new IllegalStateException("no open session");
}
if (session.getTransactionID() == null) {
throw new IllegalStateException("no transaction initiated");
}
blockingStub.rollback(Empty.getDefaultInstance());
session.setTransactionID(null);
}
public void sqlExec(String stmt, SQLValue... params) throws SQLException {
sqlExec(stmt, sqlNameParams(params));
}
public synchronized void sqlExec(String stmt, Map<String, SQLValue> params) throws SQLException {
if (session == null) {
throw new IllegalStateException("no open session");
}
if (session.getTransactionID() == null) {
throw new IllegalStateException("no transaction initiated");
}
final ImmudbProto.SQLExecRequest req = ImmudbProto.SQLExecRequest.newBuilder()
.setSql(stmt)
.addAllParams(sqlEncodeParams(params))
.build();
blockingStub.txSQLExec(req);
}
public SQLQueryResult sqlQuery(String stmt, SQLValue... params) throws SQLException {
return sqlQuery(stmt, sqlNameParams(params));
}
public synchronized SQLQueryResult sqlQuery(String stmt, Map<String, SQLValue> params) throws SQLException {
if (session == null) {
throw new IllegalStateException("no open session");
}
if (session.getTransactionID() == null) {
throw new IllegalStateException("no transaction initiated");
}
final ImmudbProto.SQLQueryRequest req = ImmudbProto.SQLQueryRequest.newBuilder()
.setSql(stmt)
.addAllParams(sqlEncodeParams(params))
.build();
return new SQLQueryResult(blockingStub.txSQLQuery(req));
}
private Map<String, SQLValue> sqlNameParams(SQLValue... params) {
final Map<String, SQLValue> nparams = new HashMap<>(params.length);
for (int i = 1; i <= params.length; i++) {
nparams.put("param" + i, params[i-1]);
}
return nparams;
}
private Iterable<NamedParam> sqlEncodeParams(Map<String, SQLValue> params) {
List<ImmudbProto.NamedParam> nparams = new ArrayList<>();
for (Map.Entry<String, SQLValue> p : params.entrySet()) {
nparams.add(NamedParam.newBuilder()
.setName(p.getKey())
.setValue(p.getValue().asProtoSQLValue())
.build()
);
}
return nparams;
}
//
// ========== DATABASE ==========
//
public void createDatabase(String database) {
createDatabase(database, false);
}
public synchronized void createDatabase(String database, boolean ifNotExists) {
if (session == null) {
throw new IllegalStateException("no open session");
}
final ImmudbProto.CreateDatabaseRequest req = ImmudbProto.CreateDatabaseRequest.newBuilder()
.setName(database)
.setIfNotExists(ifNotExists)
.build();
blockingStub.createDatabaseV2(req);
}
// LoadDatabase loads database on the server. A database is not loaded
// if it has AutoLoad setting set to false or if it failed to load during
// immudb startup.
//
// This call requires SysAdmin permission level or admin permission to the
// database.
public synchronized void loadDatabase(String database) {
if (session == null) {
throw new IllegalStateException("no open session");
}
final ImmudbProto.LoadDatabaseRequest req = ImmudbProto.LoadDatabaseRequest.newBuilder()
.setDatabase(database)
.build();
blockingStub.loadDatabase(req);
}
// UnloadDatabase unloads database on the server. Such database becomes
// inaccessible
// by the client and server frees internal resources allocated for that
// database.
//
// This call requires SysAdmin permission level or admin permission to the
// database.
public synchronized void unloadDatabase(String database) {
if (session == null) {
throw new IllegalStateException("no open session");
}
final ImmudbProto.UnloadDatabaseRequest req = ImmudbProto.UnloadDatabaseRequest.newBuilder()
.setDatabase(database)
.build();
blockingStub.unloadDatabase(req);
}
// DeleteDatabase removes an unloaded database.
// This also removes locally stored files used by the database.
//
// This call requires SysAdmin permission level or admin permission to the
// database.
public synchronized void deleteDatabase(String database) {
if (session == null) {
throw new IllegalStateException("no open session");
}
final ImmudbProto.DeleteDatabaseRequest req = ImmudbProto.DeleteDatabaseRequest.newBuilder()
.setDatabase(database)
.build();
blockingStub.deleteDatabase(req);
}
public synchronized List<String> databases() {
if (session == null) {
throw new IllegalStateException("no open session");
}
final ImmudbProto.DatabaseListRequestV2 req = ImmudbProto.DatabaseListRequestV2.newBuilder().build();
final ImmudbProto.DatabaseListResponseV2 resp = blockingStub.databaseListV2(req);
final List<String> list = new ArrayList<>(resp.getDatabasesCount());
for (ImmudbProto.DatabaseWithSettings db : resp.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 synchronized 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(blockingStub.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 synchronized 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(blockingStub.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 synchronized 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(blockingStub.get(req));
} catch (StatusRuntimeException e) {
if (e.getMessage().contains("key not found")) {
throw new KeyNotFoundException();
}
throw e;
}
}
public synchronized 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 = blockingStub.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 synchronized Entry verifiedGetAtTx(byte[] key, long tx) throws KeyNotFoundException, VerificationException {
final ImmuState state = state();
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 synchronized Entry verifiedGetSinceTx(byte[] key, long tx)
throws KeyNotFoundException, VerificationException {
final ImmuState state = state();
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 synchronized Entry verifiedGetAtRevision(byte[] key, long rev)
throws KeyNotFoundException, VerificationException {
final ImmuState state = state();
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.getTxId())
.build();
final ImmudbProto.VerifiableEntry vEntry;
try {
vEntry = blockingStub.verifiableGet(vGetReq);
} catch (StatusRuntimeException e) {
if (e.getMessage().contains("key not found")) {
throw new KeyNotFoundException();
}
throw e;
}
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 VerificationException("Data is corrupted: entry does not belong to specified key");
}
if (entry.getReferenceBy() != null
&& !Arrays.equals(keyReq.getKey().toByteArray(), entry.getReferenceBy().getKey())) {
throw new VerificationException("Data is corrupted: entry does not belong to specified key");
}
if (entry.getMetadata() != null && entry.getMetadata().deleted()) {
throw new VerificationException("Data is corrupted: entry is marked as deleted");
}
if (keyReq.getAtTx() != 0 && entry.getTx() != keyReq.getAtTx()) {
throw new VerificationException("Data is corrupted: entry does not belong to specified tx");
}
if (state.getTxId() <= entry.getTx()) {
final byte[] digest = vEntry.getVerifiableTx().getDualProof().getTargetTxHeader().getEH().toByteArray();
eh = CryptoUtils.digestFrom(digest);
sourceId = state.getTxId();
sourceAlh = CryptoUtils.digestFrom(state.getTxHash());
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.getTxId();
targetAlh = CryptoUtils.digestFrom(state.getTxHash());
}
final byte[] kvDigest = entry.digestFor(vEntry.getVerifiableTx().getTx().getHeader().getVersion());
if (!CryptoUtils.verifyInclusion(inclusionProof, kvDigest, eh)) {
throw new VerificationException("Inclusion verification failed.");
}
if (state.getTxId() > 0) {
if (!CryptoUtils.verifyDualProof(
dualProof,
sourceId,
targetId,
sourceAlh,
targetAlh)) {
throw new VerificationException("Dual proof verification failed.");
}
}
final ImmuState newState = new ImmuState(
session.getDatabase(),
targetId,
targetAlh,
vEntry.getVerifiableTx().getSignature().toByteArray());
if (!newState.checkSignature(serverSigningKey)) {
throw new VerificationException("State signature verification failed");
}
stateHolder.setState(newState);
return Entry.valueOf(vEntry.getEntry());
}
//
// ========== DELETE ==========
//
public TxHeader delete(String key) throws KeyNotFoundException {
return delete(Utils.toByteArray(key));
}
public synchronized TxHeader delete(byte[] key) throws KeyNotFoundException {
try {
final ImmudbProto.DeleteKeysRequest req = ImmudbProto.DeleteKeysRequest.newBuilder()
.addKeys(Utils.toByteString(key))
.build();
return TxHeader.valueOf(blockingStub.delete(req));
} catch (StatusRuntimeException e) {
if (e.getMessage().contains("key not found")) {
throw new KeyNotFoundException();
}
throw e;
}
}
//
// ========== HISTORY ==========
//
public List<Entry> historyAll(String key, long offset, boolean desc, int limit) throws KeyNotFoundException {
return historyAll(Utils.toByteArray(key), offset, desc, limit);
}
public synchronized List<Entry> historyAll(byte[] key, long offset, boolean desc, int limit)
throws KeyNotFoundException {
try {
ImmudbProto.Entries entries = blockingStub.history(ImmudbProto.HistoryRequest.newBuilder()
.setKey(Utils.toByteString(key))
.setDesc(desc)
.setOffset(offset)
.setLimit(limit)
.build());
return buildList(entries);
} catch (StatusRuntimeException e) {
if (e.getMessage().contains("key not found")) {
throw new KeyNotFoundException();
}
throw e;
}
}
//
// ========== SCAN ==========
//
public List<Entry> scanAll(String prefix) {
return scanAll(Utils.toByteArray(prefix));
}
public List<Entry> scanAll(byte[] prefix) {
return scanAll(prefix, false, 0);
}
public List<Entry> scanAll(String prefix, boolean desc, long limit) {
return scanAll(Utils.toByteArray(prefix), null, desc, limit);
}
public List<Entry> scanAll(byte[] prefix, boolean desc, long limit) {
return scanAll(prefix, null, desc, limit);
}
public List<Entry> scanAll(byte[] prefix, byte[] seekKey, boolean desc, long limit) {
return scanAll(prefix, seekKey, null, desc, limit);
}
public List<Entry> scanAll(byte[] prefix, byte[] seekKey, byte[] endKey, boolean desc, long limit) {
return scanAll(prefix, seekKey, endKey, false, false, desc, limit);
}
public synchronized List<Entry> scanAll(byte[] prefix, byte[] seekKey, byte[] endKey, boolean inclusiveSeek,
boolean inclusiveEnd,
boolean desc, long limit) {
final ImmudbProto.ScanRequest req = ScanRequest.newBuilder()
.setPrefix(Utils.toByteString(prefix))
.setSeekKey(Utils.toByteString(seekKey))
.setEndKey(Utils.toByteString(endKey))
.setInclusiveSeek(inclusiveSeek)
.setInclusiveEnd(inclusiveEnd)
.setDesc(desc)
.setLimit(limit)
.build();
final ImmudbProto.Entries entries = blockingStub.scan(req);
return buildList(entries);
}
//
// ========== SET ==========
//
public TxHeader set(String key, byte[] value) throws CorruptedDataException {
return set(Utils.toByteArray(key), value);
}
public synchronized 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 = blockingStub.set(req);
if (txHdr.getNentries() != 1) {
throw new CorruptedDataException();
}
return TxHeader.valueOf(txHdr);
}
public synchronized 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 = blockingStub.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 synchronized 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 = blockingStub.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 synchronized 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.getTxId())
.build();
final ImmudbProto.VerifiableTx vtx = blockingStub.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 VerificationException("State signature verification failed");
}
stateHolder.setState(newState);
return TxHeader.valueOf(vtx.getTx().getHeader());
}
public TxHeader verifiedSetReference(byte[] key, byte[] referencedKey) throws VerificationException {
return verifiedSetReference(key, referencedKey, 0);
}
public synchronized 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.getTxId())
.build();
final ImmudbProto.VerifiableTx vtx = blockingStub.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 VerificationException("State signature verification failed");
}
stateHolder.setState(newState);
return TxHeader.valueOf(vtx.getTx().getHeader());
}
private ImmuState verifyDualProof(ImmudbProto.VerifiableTx vtx, Tx tx, ImmuState state)
throws VerificationException {
final long sourceId = state.getTxId();
final long targetId = tx.getHeader().getId();
final byte[] sourceAlh = CryptoUtils.digestFrom(state.getTxHash());
final byte[] targetAlh = tx.getHeader().alh();
if (state.getTxId() > 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(state.getDatabase(), 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);
}