Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2026-10-06 6bac54b555d27f1a85c1e4f011a6e7bd9111b0d0
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
#include "dbms_blockchain_table.hpp"
 
#include <cctype>
#include <sstream>
#include <string>
#include <vector>
 
extern "C"
{
#include "access/htup_details.h"
#include "catalog/namespace.h"
#include "catalog/pg_type.h"
#include "commands/trigger.h"
#include "common/cryptohash.h"
#include "common/sha2.h"
#include "executor/spi.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/elog.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#include "utils/timestamp.h"
}
 
#define RUDB_DBMS_BLOCKCHAIN_TABLE_VERSION "0.1.0"
#define BCT_DATA_FORMAT 1
#define BCT_INSTANCE_ID 1
#define BCT_DEFAULT_CHAINS 32
#define BCT_SIGN_ALGO_DEFAULT 3
 
namespace
{
struct BlockchainTable
{
    int64 table_id = 0;
    Oid table_oid = InvalidOid;
    int32 chains_count = BCT_DEFAULT_CHAINS;
    int32 hash_algo = 3;
    bool retention_is_null = true;
    Datum retention = (Datum) 0;
};
 
static std::string
text_to_string(text *value)
{
    if (value == nullptr)
        return std::string();
    return std::string(VARDATA_ANY(value), VARSIZE_ANY_EXHDR(value));
}
 
static std::string
quote_ident_cpp(const std::string &value)
{
    std::string out = "\"";
    for (char ch : value)
    {
        if (ch == '"')
            out += "\"\"";
        else
            out += ch;
    }
    out += "\"";
    return out;
}
 
static std::string
qualified_name(const std::string &schema_name, const std::string &table_name)
{
    return quote_ident_cpp(schema_name) + "." + quote_ident_cpp(table_name);
}
 
static bytea *
bytea_from_bytes(const std::string &bytes)
{
    bytea *result = (bytea *) palloc(VARHDRSZ + bytes.size());
    SET_VARSIZE(result, VARHDRSZ + bytes.size());
    if (!bytes.empty())
        memcpy(VARDATA(result), bytes.data(), bytes.size());
    return result;
}
 
static void
append_u32(std::string &out, uint32 value)
{
    out.push_back((char) ((value >> 24) & 0xff));
    out.push_back((char) ((value >> 16) & 0xff));
    out.push_back((char) ((value >> 8) & 0xff));
    out.push_back((char) (value & 0xff));
}
 
static void
append_bytea(std::string &out, bytea *value)
{
    if (value == nullptr)
        return;
    out.append((const char *) VARDATA_ANY(value), VARSIZE_ANY_EXHDR(value));
}
 
static std::string
bytea_to_hex(bytea *value)
{
    static const char hexdigits[] = "0123456789abcdef";
    std::string out;
 
    if (value == nullptr)
        return out;
 
    out.reserve(VARSIZE_ANY_EXHDR(value) * 2);
    for (int i = 0; i < VARSIZE_ANY_EXHDR(value); ++i)
    {
        unsigned char ch = ((const unsigned char *) VARDATA_ANY(value))[i];
        out.push_back(hexdigits[(ch >> 4) & 0x0f]);
        out.push_back(hexdigits[ch & 0x0f]);
    }
 
    return out;
}
 
static std::string
json_escape(const std::string &value)
{
    std::string out;
 
    out.reserve(value.size() + 8);
    for (char ch : value)
    {
        switch (ch)
        {
            case '"':
                out += "\\\"";
                break;
            case '\\':
                out += "\\\\";
                break;
            case '\b':
                out += "\\b";
                break;
            case '\f':
                out += "\\f";
                break;
            case '\n':
                out += "\\n";
                break;
            case '\r':
                out += "\\r";
                break;
            case '\t':
                out += "\\t";
                break;
            default:
                if ((unsigned char) ch < 0x20)
                {
                    static const char hexdigits[] = "0123456789abcdef";
                    out += "\\u00";
                    out.push_back(hexdigits[((unsigned char) ch >> 4) & 0x0f]);
                    out.push_back(hexdigits[(unsigned char) ch & 0x0f]);
                }
                else
                    out.push_back(ch);
                break;
        }
    }
 
    return out;
}
 
static bytea *
hash_sha512(bytea *input)
{
    pg_cryptohash_ctx *ctx;
    bytea *result;
 
    result = (bytea *) palloc(VARHDRSZ + PG_SHA512_DIGEST_LENGTH);
    SET_VARSIZE(result, VARHDRSZ + PG_SHA512_DIGEST_LENGTH);
 
    ctx = pg_cryptohash_create(PG_SHA512);
    if (ctx == NULL)
        ereport(ERROR, (errcode(ERRCODE_OUT_OF_MEMORY), errmsg("out of memory")));
 
    if (pg_cryptohash_init(ctx) < 0 ||
        pg_cryptohash_update(ctx, (const uint8 *) VARDATA_ANY(input), VARSIZE_ANY_EXHDR(input)) < 0 ||
        pg_cryptohash_final(ctx, (uint8 *) VARDATA(result), PG_SHA512_DIGEST_LENGTH) < 0)
    {
        const char *err = pg_cryptohash_error(ctx);
        pg_cryptohash_free(ctx);
        ereport(ERROR,
                (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
                 errmsg("%s", err ? err : "cryptohash failed")));
    }
 
    pg_cryptohash_free(ctx);
    return result;
}
 
static bool
is_bct_hash_excluded_column(const char *name)
{
    return pg_strcasecmp(name, "orabctab_hash$") == 0 ||
           pg_strcasecmp(name, "orabctab_signature$") == 0 ||
           pg_strcasecmp(name, "orabctab_signature_alg$") == 0 ||
           pg_strcasecmp(name, "orabctab_signature_cert$") == 0 ||
           pg_strcasecmp(name, "orabctab_spare$") == 0;
}
 
static int
attnum_or_error(TupleDesc desc, const char *name)
{
    int attnum = SPI_fnumber(desc, name);
    if (attnum <= 0)
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_COLUMN),
                 errmsg("blockchain service column \"%s\" does not exist", name)));
    return attnum;
}
 
static std::string
datum_to_stable_bytes(Datum value, Oid typid)
{
    Oid outfunc;
    bool isvarlena;
    char *out;
    std::string result;
 
    if (typid == BYTEAOID)
    {
        bytea *raw = DatumGetByteaPP(value);
        result.assign((const char *) VARDATA_ANY(raw), VARSIZE_ANY_EXHDR(raw));
        if ((Pointer) raw != DatumGetPointer(value))
            pfree(raw);
        return result;
    }
 
    getTypeOutputInfo(typid, &outfunc, &isvarlena);
    out = OidOutputFunctionCall(outfunc, value);
    result = out ? out : "";
    if (out)
        pfree(out);
 
    return result;
}
 
static bytea *
build_row_hash_bytes(TupleDesc desc, HeapTuple tuple, bytea *previous_hash)
{
    std::string out;
 
    for (int i = 0; i < desc->natts; ++i)
    {
        Form_pg_attribute attr = TupleDescAttr(desc, i);
        if (attr->attisdropped)
            continue;
 
        const char *attname = NameStr(attr->attname);
        if (is_bct_hash_excluded_column(attname))
            continue;
 
        bool isnull = false;
        Datum value = heap_getattr(tuple, attr->attnum, desc, &isnull);
        std::string bytes;
 
        if (!isnull)
            bytes = datum_to_stable_bytes(value, attr->atttypid);
 
        append_u32(out, BCT_DATA_FORMAT);
        append_u32(out, (uint32) attr->attnum);
        append_u32(out, (uint32) attr->atttypid);
        append_u32(out, isnull ? 1 : 0);
        append_u32(out, (uint32) bytes.size());
        out.append(bytes);
    }
 
    append_u32(out, previous_hash ? (uint32) VARSIZE_ANY_EXHDR(previous_hash) : 0);
    append_bytea(out, previous_hash);
 
    return bytea_from_bytes(out);
}
 
static void
spi_connect_or_error()
{
    if (SPI_connect() != SPI_OK_CONNECT)
        ereport(ERROR, (errmsg("SPI_connect failed")));
}
 
static void
spi_finish_or_error()
{
    if (SPI_finish() != SPI_OK_FINISH)
        ereport(ERROR, (errmsg("SPI_finish failed")));
}
 
static void
spi_exec(const std::string &sql)
{
    int rc = SPI_execute(sql.c_str(), false, 0);
    if (rc < 0)
        ereport(ERROR, (errmsg("SPI_execute failed for DBMS_BLOCKCHAIN_TABLE command")));
}
 
static BlockchainTable
load_blockchain_table_by_oid(Oid table_oid)
{
    BlockchainTable table;
    Oid argtypes[1] = {OIDOID};
    Datum values[1] = {ObjectIdGetDatum(table_oid)};
    char nulls[1] = {' '};
 
    int rc = SPI_execute_with_args(
        "SELECT table_id, table_oid, chains_count, hash_algo, retention_seconds "
        "FROM \"SYS\".dbms_blockchain_tables WHERE table_oid = $1 AND enabled",
        1, argtypes, values, nulls, true, 1);
 
    if (rc != SPI_OK_SELECT || SPI_processed != 1)
        ereport(ERROR,
                (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                 errmsg("table is not registered as blockchain table")));
 
    HeapTuple tup = SPI_tuptable->vals[0];
    TupleDesc desc = SPI_tuptable->tupdesc;
    bool isnull = false;
 
    table.table_id = DatumGetInt64(SPI_getbinval(tup, desc, 1, &isnull));
    table.table_oid = DatumGetObjectId(SPI_getbinval(tup, desc, 2, &isnull));
    table.chains_count = DatumGetInt32(SPI_getbinval(tup, desc, 3, &isnull));
    table.hash_algo = DatumGetInt32(SPI_getbinval(tup, desc, 4, &isnull));
    table.retention = SPI_getbinval(tup, desc, 5, &table.retention_is_null);
 
    return table;
}
 
static Oid
resolve_table_oid(const std::string &schema_name, const std::string &table_name)
{
    Oid nspoid = LookupExplicitNamespace(schema_name.c_str(), false);
    Oid relid = get_relname_relid(table_name.c_str(), nspoid);
 
    if (!OidIsValid(relid))
        ereport(ERROR,
                (errcode(ERRCODE_UNDEFINED_TABLE),
                 errmsg("table \"%s.%s\" does not exist", schema_name.c_str(), table_name.c_str())));
 
    return relid;
}
 
static bytea *
fetch_previous_hash(const std::string &schema_name,
                    const std::string &table_name,
                    int32 instance_id,
                    int32 chain_id,
                    int64 sequence_id)
{
    if (sequence_id <= 1)
        return nullptr;
 
    std::ostringstream sql;
    sql << "SELECT orabctab_hash$ FROM " << qualified_name(schema_name, table_name)
        << " WHERE orabctab_inst_id$ = " << instance_id
        << " AND orabctab_chain_id$ = " << chain_id
        << " AND orabctab_seq_num$ = " << (sequence_id - 1);
 
    int rc = SPI_execute(sql.str().c_str(), true, 1);
    if (rc != SPI_OK_SELECT || SPI_processed == 0)
        return nullptr;
 
    bool isnull = false;
    Datum value = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
    if (isnull)
        return nullptr;
 
    return DatumGetByteaPP(value);
}
 
static HeapTuple
fetch_blockchain_row(const std::string &schema_name,
                     const std::string &table_name,
                     int32 instance_id,
                     int32 chain_id,
                     int64 sequence_id,
                     TupleDesc *out_desc)
{
    std::ostringstream sql;
    sql << "SELECT * FROM " << qualified_name(schema_name, table_name)
        << " WHERE orabctab_inst_id$ = " << instance_id
        << " AND orabctab_chain_id$ = " << chain_id
        << " AND orabctab_seq_num$ = " << sequence_id;
 
    int rc = SPI_execute(sql.str().c_str(), true, 1);
    if (rc != SPI_OK_SELECT || SPI_processed != 1)
        ereport(ERROR,
                (errcode(ERRCODE_NO_DATA_FOUND),
                 errmsg("blockchain row not found")));
 
    *out_desc = SPI_tuptable->tupdesc;
    return SPI_tuptable->vals[0];
}
 
static bytea *
make_signature_placeholder(bytea *signed_bytes, bytea *certificate_guid, int32 signature_algo)
{
    std::string bytes;
    bytes.append((const char *) VARDATA_ANY(signed_bytes), VARSIZE_ANY_EXHDR(signed_bytes));
    if (certificate_guid)
        bytes.append((const char *) VARDATA_ANY(certificate_guid), VARSIZE_ANY_EXHDR(certificate_guid));
    append_u32(bytes, (uint32) signature_algo);
    return hash_sha512(bytea_from_bytes(bytes));
}
 
static Datum
jsonb_from_string(const std::string &json)
{
    return DirectFunctionCall1(jsonb_in, CStringGetDatum(json.c_str()));
}
 
} // namespace
 
extern "C"
{
PG_FUNCTION_INFO_V1(dbms_blockchain_table_register_table);
PG_FUNCTION_INFO_V1(dbms_blockchain_table_add_certificate);
PG_FUNCTION_INFO_V1(dbms_blockchain_table_before_insert);
PG_FUNCTION_INFO_V1(dbms_blockchain_table_no_modify);
PG_FUNCTION_INFO_V1(dbms_blockchain_table_delete_expired_rows);
PG_FUNCTION_INFO_V1(dbms_blockchain_table_get_bytes_for_row_hash);
PG_FUNCTION_INFO_V1(dbms_blockchain_table_get_bytes_for_row_signature);
PG_FUNCTION_INFO_V1(dbms_blockchain_table_sign_row);
PG_FUNCTION_INFO_V1(dbms_blockchain_table_verify_rows);
PG_FUNCTION_INFO_V1(dbms_blockchain_table_get_signed_blockchain_digest);
PG_FUNCTION_INFO_V1(dbms_blockchain_table_anchor_digest);
PG_FUNCTION_INFO_V1(dbms_blockchain_table_verify_table_blockchain);
PG_FUNCTION_INFO_V1(dbms_blockchain_table_get_version);
 
Datum
dbms_blockchain_table_get_version(PG_FUNCTION_ARGS)
{
    PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_BLOCKCHAIN_TABLE_VERSION));
}
 
Datum
dbms_blockchain_table_add_certificate(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0))
        ereport(ERROR, (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED), errmsg("DER certificate must not be NULL")));
 
    bytea *cert = PG_GETARG_BYTEA_PP(0);
    text *subject = PG_ARGISNULL(1) ? nullptr : PG_GETARG_TEXT_PP(1);
    bytea *guid;
 
    spi_connect_or_error();
    Oid argtypes[3] = {OIDOID, BYTEAOID, TEXTOID};
    Datum values[3] = {ObjectIdGetDatum(GetUserId()), PointerGetDatum(cert), subject ? PointerGetDatum(subject) : (Datum) 0};
    char nulls[3] = {' ', ' ', subject ? ' ' : 'n'};
 
    int rc = SPI_execute_with_args(
        "INSERT INTO \"SYS\".dbms_blockchain_certificates(owner_oid, der_certificate, subject_name) "
        "VALUES ($1, $2, $3) RETURNING certificate_guid",
        3, argtypes, values, nulls, false, 1);
 
    if (rc != SPI_OK_INSERT_RETURNING || SPI_processed != 1)
        ereport(ERROR, (errmsg("could not register blockchain certificate")));
 
    bool isnull = false;
    Datum guid_datum = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
    guid = DatumGetByteaPP(guid_datum);
    guid = (bytea *) SPI_palloc(VARHDRSZ + VARSIZE_ANY_EXHDR(guid));
    SET_VARSIZE(guid, VARHDRSZ + VARSIZE_ANY_EXHDR(DatumGetByteaPP(guid_datum)));
    memcpy(VARDATA(guid), VARDATA_ANY(DatumGetByteaPP(guid_datum)), VARSIZE_ANY_EXHDR(DatumGetByteaPP(guid_datum)));
    spi_finish_or_error();
 
    PG_RETURN_BYTEA_P(guid);
}
 
Datum
dbms_blockchain_table_register_table(PG_FUNCTION_ARGS)
{
    std::string schema_name = text_to_string(PG_GETARG_TEXT_PP(0));
    std::string table_name = text_to_string(PG_GETARG_TEXT_PP(1));
    int32 retention_seconds = PG_ARGISNULL(2) ? -1 : PG_GETARG_INT32(2);
    int32 chains_count = PG_ARGISNULL(3) ? BCT_DEFAULT_CHAINS : PG_GETARG_INT32(3);
    Oid relid = resolve_table_oid(schema_name, table_name);
    std::string qname = qualified_name(schema_name, table_name);
    int64 table_id = 0;
 
    if (chains_count <= 0)
        ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("chains_count must be positive")));
 
    spi_connect_or_error();
 
    Oid argtypes[6] = {TEXTOID, TEXTOID, OIDOID, OIDOID, INT4OID, INT4OID};
    Datum values[6] = {
        CStringGetTextDatum(schema_name.c_str()),
        CStringGetTextDatum(table_name.c_str()),
        ObjectIdGetDatum(relid),
        ObjectIdGetDatum(GetUserId()),
        Int32GetDatum(chains_count),
        Int32GetDatum(retention_seconds)};
    char nulls[6] = {' ', ' ', ' ', ' ', ' ', retention_seconds < 0 ? 'n' : ' '};
 
    int rc = SPI_execute_with_args(
        "INSERT INTO \"SYS\".dbms_blockchain_tables(schema_name, table_name, table_oid, owner_oid, chains_count, retention_seconds) "
        "VALUES ($1, $2, $3, $4, $5, $6) "
        "ON CONFLICT (table_oid) DO UPDATE SET chains_count = EXCLUDED.chains_count, retention_seconds = EXCLUDED.retention_seconds, enabled = true "
        "RETURNING table_id",
        6, argtypes, values, nulls, false, 1);
 
    if (rc != SPI_OK_INSERT_RETURNING && rc != SPI_OK_UPDATE_RETURNING)
        ereport(ERROR, (errmsg("could not register blockchain table")));
 
    bool isnull = false;
    table_id = DatumGetInt64(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull));
 
    spi_exec("ALTER TABLE " + qname + " ADD COLUMN IF NOT EXISTS orabctab_inst_id$ integer");
    spi_exec("ALTER TABLE " + qname + " ADD COLUMN IF NOT EXISTS orabctab_chain_id$ integer");
    spi_exec("ALTER TABLE " + qname + " ADD COLUMN IF NOT EXISTS orabctab_seq_num$ bigint");
    spi_exec("ALTER TABLE " + qname + " ADD COLUMN IF NOT EXISTS orabctab_creation_time$ timestamptz");
    spi_exec("ALTER TABLE " + qname + " ADD COLUMN IF NOT EXISTS orabctab_user_number$ oid");
    spi_exec("ALTER TABLE " + qname + " ADD COLUMN IF NOT EXISTS orabctab_hash$ bytea");
    spi_exec("ALTER TABLE " + qname + " ADD COLUMN IF NOT EXISTS orabctab_signature$ bytea");
    spi_exec("ALTER TABLE " + qname + " ADD COLUMN IF NOT EXISTS orabctab_signature_alg$ integer");
    spi_exec("ALTER TABLE " + qname + " ADD COLUMN IF NOT EXISTS orabctab_signature_cert$ bytea");
    spi_exec("ALTER TABLE " + qname + " ADD COLUMN IF NOT EXISTS orabctab_spare$ bytea");
 
    for (int32 chain = 0; chain < chains_count; ++chain)
    {
        std::ostringstream sql;
        sql << "INSERT INTO \"SYS\".dbms_blockchain_chains(table_id, instance_id, chain_id) VALUES ("
            << table_id << ", " << BCT_INSTANCE_ID << ", " << chain << ") ON CONFLICT DO NOTHING";
        spi_exec(sql.str());
    }
 
    spi_exec("DROP TRIGGER IF EXISTS dbms_blockchain_table_before_insert ON " + qname);
    spi_exec("DROP TRIGGER IF EXISTS dbms_blockchain_table_no_modify ON " + qname);
    spi_exec("CREATE TRIGGER dbms_blockchain_table_before_insert BEFORE INSERT ON " + qname +
             " FOR EACH ROW EXECUTE FUNCTION pg_catalog.dbms_blockchain_table_before_insert()");
    spi_exec("CREATE TRIGGER dbms_blockchain_table_no_modify BEFORE UPDATE OR DELETE ON " + qname +
             " FOR EACH ROW EXECUTE FUNCTION pg_catalog.dbms_blockchain_table_no_modify()");
 
    spi_finish_or_error();
    PG_RETURN_INT64(table_id);
}
 
Datum
dbms_blockchain_table_before_insert(PG_FUNCTION_ARGS)
{
    TriggerData *trigdata;
    HeapTuple tuple;
    TupleDesc desc;
    BlockchainTable table;
    int32 chain_id;
    int64 sequence_id;
    bytea *previous_hash = nullptr;
    bytea *row_bytes;
    bytea *row_hash;
 
    if (!CALLED_AS_TRIGGER(fcinfo))
        ereport(ERROR, (errmsg("dbms_blockchain_table_before_insert must be called as trigger")));
 
    trigdata = (TriggerData *) fcinfo->context;
    if (!TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
        ereport(ERROR, (errmsg("dbms_blockchain_table_before_insert supports INSERT only")));
 
    tuple = trigdata->tg_trigtuple;
    desc = RelationGetDescr(trigdata->tg_relation);
 
    spi_connect_or_error();
    table = load_blockchain_table_by_oid(RelationGetRelid(trigdata->tg_relation));
 
    chain_id = (int32) (GetCurrentTimestamp() % table.chains_count);
 
    {
        std::ostringstream sql;
        sql << "SELECT last_sequence_id + 1, last_hash FROM \"SYS\".dbms_blockchain_chains "
            << "WHERE table_id = " << table.table_id
            << " AND instance_id = " << BCT_INSTANCE_ID
            << " AND chain_id = " << chain_id
            << " FOR UPDATE";
        int rc = SPI_execute(sql.str().c_str(), false, 1);
        if (rc != SPI_OK_SELECT || SPI_processed != 1)
            ereport(ERROR, (errmsg("blockchain chain state not found")));
 
        bool isnull = false;
        sequence_id = DatumGetInt64(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull));
        Datum prev = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 2, &isnull);
        if (!isnull)
            previous_hash = DatumGetByteaPP(prev);
    }
 
    {
        int repl_cols[10];
        Datum repl_values[10];
        bool repl_nulls[10] = {false};
        int n = 0;
 
        repl_cols[n] = attnum_or_error(desc, "orabctab_inst_id$");
        repl_values[n++] = Int32GetDatum(BCT_INSTANCE_ID);
        repl_cols[n] = attnum_or_error(desc, "orabctab_chain_id$");
        repl_values[n++] = Int32GetDatum(chain_id);
        repl_cols[n] = attnum_or_error(desc, "orabctab_seq_num$");
        repl_values[n++] = Int64GetDatum(sequence_id);
        repl_cols[n] = attnum_or_error(desc, "orabctab_creation_time$");
        repl_values[n++] = TimestampTzGetDatum(GetCurrentTimestamp());
        repl_cols[n] = attnum_or_error(desc, "orabctab_user_number$");
        repl_values[n++] = ObjectIdGetDatum(GetUserId());
        repl_cols[n] = attnum_or_error(desc, "orabctab_signature$");
        repl_values[n] = (Datum) 0;
        repl_nulls[n++] = true;
        repl_cols[n] = attnum_or_error(desc, "orabctab_signature_alg$");
        repl_values[n] = (Datum) 0;
        repl_nulls[n++] = true;
        repl_cols[n] = attnum_or_error(desc, "orabctab_signature_cert$");
        repl_values[n] = (Datum) 0;
        repl_nulls[n++] = true;
        repl_cols[n] = attnum_or_error(desc, "orabctab_spare$");
        repl_values[n] = (Datum) 0;
        repl_nulls[n++] = true;
 
        tuple = heap_modify_tuple_by_cols(tuple, desc, n, repl_cols, repl_values, repl_nulls);
    }
 
    row_bytes = build_row_hash_bytes(desc, tuple, previous_hash);
    row_hash = hash_sha512(row_bytes);
 
    {
        int repl_col = attnum_or_error(desc, "orabctab_hash$");
        Datum repl_value = PointerGetDatum(row_hash);
        bool repl_null = false;
        tuple = heap_modify_tuple_by_cols(tuple, desc, 1, &repl_col, &repl_value, &repl_null);
    }
 
    {
        Oid argtypes[3] = {INT8OID, INT4OID, BYTEAOID};
        Datum values[3] = {Int64GetDatum(table.table_id), Int32GetDatum(chain_id), PointerGetDatum(row_hash)};
        char nulls[3] = {' ', ' ', ' '};
 
        int rc = SPI_execute_with_args(
            "UPDATE \"SYS\".dbms_blockchain_chains "
            "SET last_sequence_id = last_sequence_id + 1, last_hash = $3, last_creation_time = clock_timestamp() "
            "WHERE table_id = $1 AND instance_id = 1 AND chain_id = $2",
            3, argtypes, values, nulls, false, 0);
        if (rc != SPI_OK_UPDATE)
            ereport(ERROR, (errmsg("could not update blockchain chain state")));
    }
 
    spi_finish_or_error();
    return PointerGetDatum(tuple);
}
 
Datum
dbms_blockchain_table_no_modify(PG_FUNCTION_ARGS)
{
    TriggerData *trigdata;
    const char *internal_dml;
 
    if (!CALLED_AS_TRIGGER(fcinfo))
        ereport(ERROR, (errmsg("dbms_blockchain_table_no_modify must be called as trigger")));
 
    trigdata = (TriggerData *) fcinfo->context;
    internal_dml = GetConfigOptionByName("dbms_blockchain_table.internal_dml", NULL, true);
    if (internal_dml && pg_strcasecmp(internal_dml, "on") == 0)
    {
        if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
            return PointerGetDatum(trigdata->tg_newtuple);
        return PointerGetDatum(trigdata->tg_trigtuple);
    }
 
    if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
        ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                        errmsg("UPDATE is not allowed on blockchain table")));
 
    ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
                    errmsg("DELETE is not allowed on blockchain table")));
    PG_RETURN_NULL();
}
 
Datum
dbms_blockchain_table_get_bytes_for_row_hash(PG_FUNCTION_ARGS)
{
    std::string schema_name = text_to_string(PG_GETARG_TEXT_PP(0));
    std::string table_name = text_to_string(PG_GETARG_TEXT_PP(1));
    int32 instance_id = PG_GETARG_INT32(2);
    int32 chain_id = PG_GETARG_INT32(3);
    int64 sequence_id = PG_GETARG_INT64(4);
    int32 data_format = PG_GETARG_INT32(5);
    TupleDesc desc = nullptr;
    HeapTuple row;
    bytea *previous_hash;
    bytea *row_bytes;
 
    if (data_format != BCT_DATA_FORMAT)
        ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("unsupported blockchain data format")));
 
    spi_connect_or_error();
    row = fetch_blockchain_row(schema_name, table_name, instance_id, chain_id, sequence_id, &desc);
    desc = CreateTupleDescCopy(desc);
    row = heap_copytuple(row);
    previous_hash = fetch_previous_hash(schema_name, table_name, instance_id, chain_id, sequence_id);
    {
        bytea *tmp = build_row_hash_bytes(desc, row, previous_hash);
        row_bytes = (bytea *) SPI_palloc(VARSIZE_ANY(tmp));
        memcpy(row_bytes, tmp, VARSIZE_ANY(tmp));
    }
    spi_finish_or_error();
 
    PG_RETURN_BYTEA_P(row_bytes);
}
 
Datum
dbms_blockchain_table_get_bytes_for_row_signature(PG_FUNCTION_ARGS)
{
    std::string schema_name = text_to_string(PG_GETARG_TEXT_PP(0));
    std::string table_name = text_to_string(PG_GETARG_TEXT_PP(1));
    int32 instance_id = PG_GETARG_INT32(2);
    int32 chain_id = PG_GETARG_INT32(3);
    int64 sequence_id = PG_GETARG_INT64(4);
    int32 data_format = PG_GETARG_INT32(5);
    TupleDesc desc = nullptr;
    HeapTuple row;
    bytea *hash_copy;
 
    if (data_format != BCT_DATA_FORMAT)
        ereport(ERROR, (errcode(ERRCODE_INVALID_PARAMETER_VALUE), errmsg("unsupported blockchain data format")));
 
    spi_connect_or_error();
    row = fetch_blockchain_row(schema_name, table_name, instance_id, chain_id, sequence_id, &desc);
 
    bool isnull = false;
    Datum hash_datum = heap_getattr(row, attnum_or_error(desc, "orabctab_hash$"), desc, &isnull);
    if (isnull)
        ereport(ERROR, (errmsg("blockchain row hash is NULL")));
 
    bytea *hash = DatumGetByteaPP(hash_datum);
    hash_copy = (bytea *) SPI_palloc(VARSIZE_ANY(hash));
    memcpy(hash_copy, hash, VARSIZE_ANY(hash));
    spi_finish_or_error();
 
    PG_RETURN_BYTEA_P(hash_copy);
}
 
Datum
dbms_blockchain_table_sign_row(PG_FUNCTION_ARGS)
{
    std::string schema_name = text_to_string(PG_GETARG_TEXT_PP(0));
    std::string table_name = text_to_string(PG_GETARG_TEXT_PP(1));
    int32 instance_id = PG_GETARG_INT32(2);
    int32 chain_id = PG_GETARG_INT32(3);
    int64 sequence_id = PG_GETARG_INT64(4);
    bytea *expected_hash = PG_ARGISNULL(5) ? nullptr : PG_GETARG_BYTEA_PP(5);
    bytea *signature = PG_GETARG_BYTEA_PP(6);
    bytea *certificate_guid = PG_GETARG_BYTEA_PP(7);
    int32 signature_algo = PG_GETARG_INT32(8);
    TupleDesc desc = nullptr;
    HeapTuple row;
    bytea *row_hash;
    Oid row_user;
 
    spi_connect_or_error();
    row = fetch_blockchain_row(schema_name, table_name, instance_id, chain_id, sequence_id, &desc);
 
    bool isnull = false;
    row_hash = DatumGetByteaPP(heap_getattr(row, attnum_or_error(desc, "orabctab_hash$"), desc, &isnull));
    if (isnull)
        ereport(ERROR, (errmsg("blockchain row hash is NULL")));
 
    row_user = DatumGetObjectId(heap_getattr(row, attnum_or_error(desc, "orabctab_user_number$"), desc, &isnull));
    if (row_user != GetUserId())
        ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE), errmsg("only row owner can sign blockchain row")));
 
    heap_getattr(row, attnum_or_error(desc, "orabctab_signature$"), desc, &isnull);
    if (!isnull)
        ereport(ERROR, (errmsg("blockchain row is already signed")));
 
    if (expected_hash &&
        (VARSIZE_ANY_EXHDR(expected_hash) != VARSIZE_ANY_EXHDR(row_hash) ||
         memcmp(VARDATA_ANY(expected_hash), VARDATA_ANY(row_hash), VARSIZE_ANY_EXHDR(row_hash)) != 0))
        ereport(ERROR, (errmsg("expected hash does not match blockchain row hash")));
 
    SPI_execute("SET LOCAL dbms_blockchain_table.internal_dml = 'on'", false, 0);
 
    {
        Oid argtypes[6] = {BYTEAOID, BYTEAOID, INT4OID, INT4OID, INT4OID, INT8OID};
        Datum values[6] = {
            PointerGetDatum(signature), PointerGetDatum(certificate_guid), Int32GetDatum(signature_algo),
            Int32GetDatum(instance_id), Int32GetDatum(chain_id), Int64GetDatum(sequence_id)};
        char nulls[6] = {' ', ' ', ' ', ' ', ' ', ' '};
        std::string sql = "UPDATE " + qualified_name(schema_name, table_name) +
            " SET orabctab_signature$ = $1, orabctab_signature_cert$ = $2, orabctab_signature_alg$ = $3 "
            "WHERE orabctab_inst_id$ = $4 AND orabctab_chain_id$ = $5 AND orabctab_seq_num$ = $6";
        int rc = SPI_execute_with_args(sql.c_str(), 6, argtypes, values, nulls, false, 0);
        if (rc != SPI_OK_UPDATE)
            ereport(ERROR, (errmsg("could not sign blockchain row")));
    }
 
    spi_finish_or_error();
    PG_RETURN_VOID();
}
 
Datum
dbms_blockchain_table_verify_rows(PG_FUNCTION_ARGS)
{
    std::string schema_name = text_to_string(PG_GETARG_TEXT_PP(0));
    std::string table_name = text_to_string(PG_GETARG_TEXT_PP(1));
    bool low_is_null = PG_ARGISNULL(2);
    bool high_is_null = PG_ARGISNULL(3);
    bool instance_is_null = PG_ARGISNULL(4);
    bool chain_is_null = PG_ARGISNULL(5);
    TimestampTz low_ts = low_is_null ? 0 : PG_GETARG_TIMESTAMPTZ(2);
    TimestampTz high_ts = high_is_null ? 0 : PG_GETARG_TIMESTAMPTZ(3);
    int32 instance_id = instance_is_null ? 0 : PG_GETARG_INT32(4);
    int32 chain_id = chain_is_null ? 0 : PG_GETARG_INT32(5);
    bool verify_signature = PG_ARGISNULL(6) ? true : PG_GETARG_BOOL(6);
    int64 verified = 0;
 
    if (!chain_is_null && instance_is_null)
        ereport(ERROR, (errmsg("instance_id must be specified when chain_id is specified")));
    if (!low_is_null && !high_is_null && high_ts <= low_ts)
        ereport(ERROR, (errmsg("high_timestamp must be later than low_timestamp")));
 
    spi_connect_or_error();
 
    {
        std::ostringstream sql;
        sql << "SELECT * FROM " << qualified_name(schema_name, table_name) << " WHERE true";
        if (!low_is_null)
            sql << " AND orabctab_creation_time$ >= " << "'" << timestamptz_to_str(low_ts) << "'";
        if (!high_is_null)
            sql << " AND orabctab_creation_time$ <= " << "'" << timestamptz_to_str(high_ts) << "'";
        if (!instance_is_null)
            sql << " AND orabctab_inst_id$ = " << instance_id;
        if (!chain_is_null)
            sql << " AND orabctab_chain_id$ = " << chain_id;
        sql << " ORDER BY orabctab_inst_id$, orabctab_chain_id$, orabctab_seq_num$";
 
        int rc = SPI_execute(sql.str().c_str(), true, 0);
        if (rc != SPI_OK_SELECT)
            ereport(ERROR, (errmsg("could not scan blockchain table")));
 
        uint64 processed = SPI_processed;
        TupleDesc scan_desc = CreateTupleDescCopy(SPI_tuptable->tupdesc);
        std::vector<HeapTuple> rows;
        rows.reserve(processed);
        for (uint64 i = 0; i < processed; ++i)
            rows.push_back(heap_copytuple(SPI_tuptable->vals[i]));
 
        for (uint64 i = 0; i < processed; ++i)
        {
            HeapTuple row = rows[i];
            TupleDesc desc = scan_desc;
            bool isnull = false;
            int32 row_instance = DatumGetInt32(heap_getattr(row, attnum_or_error(desc, "orabctab_inst_id$"), desc, &isnull));
            int32 row_chain = DatumGetInt32(heap_getattr(row, attnum_or_error(desc, "orabctab_chain_id$"), desc, &isnull));
            int64 row_sequence = DatumGetInt64(heap_getattr(row, attnum_or_error(desc, "orabctab_seq_num$"), desc, &isnull));
            bytea *stored_hash = DatumGetByteaPP(heap_getattr(row, attnum_or_error(desc, "orabctab_hash$"), desc, &isnull));
            bytea *prev_hash = fetch_previous_hash(schema_name, table_name, row_instance, row_chain, row_sequence);
            bytea *bytes = build_row_hash_bytes(desc, row, prev_hash);
            bytea *expected = hash_sha512(bytes);
 
            if (VARSIZE_ANY_EXHDR(stored_hash) != VARSIZE_ANY_EXHDR(expected) ||
                memcmp(VARDATA_ANY(stored_hash), VARDATA_ANY(expected), VARSIZE_ANY_EXHDR(expected)) != 0)
                ereport(ERROR, (errmsg("blockchain hash verification failed")));
 
            if (verify_signature)
            {
                heap_getattr(row, attnum_or_error(desc, "orabctab_signature$"), desc, &isnull);
                if (!isnull)
                {
                    heap_getattr(row, attnum_or_error(desc, "orabctab_signature_cert$"), desc, &isnull);
                    if (isnull)
                        ereport(ERROR, (errmsg("blockchain signature certificate is NULL")));
                }
            }
 
            verified++;
        }
    }
 
    spi_finish_or_error();
    PG_RETURN_INT64(verified);
}
 
Datum
dbms_blockchain_table_delete_expired_rows(PG_FUNCTION_ARGS)
{
    std::string schema_name = text_to_string(PG_GETARG_TEXT_PP(0));
    std::string table_name = text_to_string(PG_GETARG_TEXT_PP(1));
    bool before_is_null = PG_ARGISNULL(2);
    TimestampTz before_ts = before_is_null ? 0 : PG_GETARG_TIMESTAMPTZ(2);
    Oid relid = resolve_table_oid(schema_name, table_name);
    int64 deleted = 0;
 
    spi_connect_or_error();
    BlockchainTable table = load_blockchain_table_by_oid(relid);
    if (table.retention_is_null)
        ereport(ERROR, (errmsg("blockchain table has no retention period")));
 
    SPI_execute("SET LOCAL dbms_blockchain_table.internal_dml = 'on'", false, 0);
 
    {
        std::ostringstream sql;
        sql << "DELETE FROM " << qualified_name(schema_name, table_name)
            << " WHERE orabctab_creation_time$ < clock_timestamp() - make_interval(secs => "
            << "(SELECT retention_seconds FROM \"SYS\".dbms_blockchain_tables WHERE table_oid = '" << relid << "'::oid))";
        if (!before_is_null)
            sql << " AND orabctab_creation_time$ < '" << timestamptz_to_str(before_ts) << "'";
        int rc = SPI_execute(sql.str().c_str(), false, 0);
        if (rc != SPI_OK_DELETE)
            ereport(ERROR, (errmsg("could not delete expired blockchain rows")));
        deleted = SPI_processed;
    }
 
    spi_finish_or_error();
    PG_RETURN_INT64(deleted);
}
 
Datum
dbms_blockchain_table_get_signed_blockchain_digest(PG_FUNCTION_ARGS)
{
    std::string schema_name = text_to_string(PG_GETARG_TEXT_PP(0));
    std::string table_name = text_to_string(PG_GETARG_TEXT_PP(1));
    int32 signature_algo = PG_ARGISNULL(2) ? BCT_SIGN_ALGO_DEFAULT : PG_GETARG_INT32(2);
    Oid relid = resolve_table_oid(schema_name, table_name);
    bytea *cert_guid = nullptr;
    bytea *signed_bytes;
    bytea *signature;
    std::string rows_json = "[";
    TupleDesc out_desc;
    Datum values[4];
    bool nulls[4] = {false, false, false, false};
 
    if (get_call_result_type(fcinfo, NULL, &out_desc) != TYPEFUNC_COMPOSITE)
        ereport(ERROR, (errmsg("record return type is required")));
 
    spi_connect_or_error();
    BlockchainTable table = load_blockchain_table_by_oid(relid);
 
    Oid cert_argtypes[1] = {OIDOID};
    Datum cert_values[1] = {ObjectIdGetDatum(GetUserId())};
    char cert_nulls[1] = {' '};
    int rc = SPI_execute_with_args(
        "SELECT certificate_guid FROM \"SYS\".dbms_blockchain_certificates "
        "WHERE owner_oid = $1 AND revoked_at IS NULL ORDER BY created_at DESC LIMIT 1",
        1, cert_argtypes, cert_values, cert_nulls, true, 1);
    if (rc != SPI_OK_SELECT || SPI_processed != 1)
        ereport(ERROR, (errmsg("current user has no registered blockchain certificate")));
 
    {
        bool isnull = false;
        Datum cert = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
        if (!isnull)
        {
            bytea *cert_raw = DatumGetByteaPP(cert);
            cert_guid = (bytea *) SPI_palloc(VARSIZE_ANY(cert_raw));
            memcpy(cert_guid, cert_raw, VARSIZE_ANY(cert_raw));
        }
    }
 
    {
        std::ostringstream sql;
        sql << "SELECT instance_id, chain_id, last_sequence_id, last_creation_time, encode(last_hash, 'hex') "
            << "FROM \"SYS\".dbms_blockchain_chains WHERE table_id = " << table.table_id
            << " AND last_sequence_id > 0 ORDER BY instance_id, chain_id";
        rc = SPI_execute(sql.str().c_str(), true, 0);
        if (rc != SPI_OK_SELECT)
            ereport(ERROR, (errmsg("could not build blockchain digest")));
 
        for (uint64 i = 0; i < SPI_processed; ++i)
        {
            if (i > 0)
                rows_json += ",";
            bool isnull = false;
            HeapTuple row = SPI_tuptable->vals[i];
            TupleDesc desc = SPI_tuptable->tupdesc;
            rows_json += "{";
            rows_json += "\"instance_id\":" + std::to_string(DatumGetInt32(SPI_getbinval(row, desc, 1, &isnull)));
            rows_json += ",\"chain_id\":" + std::to_string(DatumGetInt32(SPI_getbinval(row, desc, 2, &isnull)));
            rows_json += ",\"sequence_id\":" + std::to_string(DatumGetInt64(SPI_getbinval(row, desc, 3, &isnull)));
            rows_json += ",\"creation_time\":\"";
            Datum ts = SPI_getbinval(row, desc, 4, &isnull);
            rows_json += isnull ? "" : timestamptz_to_str(DatumGetTimestampTz(ts));
            rows_json += "\",\"hash\":\"";
            Datum hash_hex = SPI_getbinval(row, desc, 5, &isnull);
            if (!isnull)
                rows_json += text_to_string(DatumGetTextPP(hash_hex));
            rows_json += "\"}";
        }
    }
    rows_json += "]";
 
    {
        std::string payload = "{\"schema_name\":\"" + schema_name + "\",\"table_name\":\"" + table_name +
                              "\",\"table_oid\":\"" + std::to_string(relid) + "\",\"rows\":" + rows_json + "}";
        signed_bytes = bytea_from_bytes(payload);
        signature = make_signature_placeholder(signed_bytes, cert_guid, signature_algo);
    }
 
    {
        Oid argtypes[5] = {INT8OID, BYTEAOID, BYTEAOID, BYTEAOID, INT4OID};
        Datum args[5] = {
            Int64GetDatum(table.table_id),
            PointerGetDatum(signed_bytes),
            PointerGetDatum(signature),
            PointerGetDatum(cert_guid),
            Int32GetDatum(signature_algo)};
        char argnulls[5] = {' ', ' ', ' ', cert_guid ? ' ' : 'n', ' '};
        SPI_execute_with_args(
            "INSERT INTO \"SYS\".dbms_blockchain_digests(table_id, signed_bytes, signature, certificate_guid, signature_algo) "
            "VALUES ($1, $2, $3, $4, $5)",
            5, argtypes, args, argnulls, false, 0);
    }
 
    values[0] = PointerGetDatum(signature);
    values[1] = PointerGetDatum(signed_bytes);
    values[2] = jsonb_from_string(rows_json);
    values[3] = PointerGetDatum(cert_guid);
 
    spi_finish_or_error();
    PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(out_desc, values, nulls)));
}
 
Datum
dbms_blockchain_table_anchor_digest(PG_FUNCTION_ARGS)
{
    std::string schema_name = text_to_string(PG_GETARG_TEXT_PP(0));
    std::string table_name = text_to_string(PG_GETARG_TEXT_PP(1));
    int32 signature_algo = PG_ARGISNULL(2) ? BCT_SIGN_ALGO_DEFAULT : PG_GETARG_INT32(2);
    Oid relid = resolve_table_oid(schema_name, table_name);
    bytea *cert_guid = nullptr;
    bytea *signed_bytes;
    bytea *signature;
    bytea *signed_bytes_hash;
    bytea *anchor_hash;
    bytea *previous_anchor_hash = nullptr;
    std::string rows_json = "[";
    std::string anchor_body;
    std::string anchor_json;
    Datum result;
    int64 digest_id = 0;
 
    spi_connect_or_error();
    BlockchainTable table = load_blockchain_table_by_oid(relid);
 
    Oid cert_argtypes[1] = {OIDOID};
    Datum cert_values[1] = {ObjectIdGetDatum(GetUserId())};
    char cert_nulls[1] = {' '};
    int rc = SPI_execute_with_args(
        "SELECT certificate_guid FROM \"SYS\".dbms_blockchain_certificates "
        "WHERE owner_oid = $1 AND revoked_at IS NULL ORDER BY created_at DESC LIMIT 1",
        1, cert_argtypes, cert_values, cert_nulls, true, 1);
    if (rc != SPI_OK_SELECT || SPI_processed != 1)
        ereport(ERROR, (errmsg("current user has no registered blockchain certificate")));
 
    {
        bool isnull = false;
        Datum cert = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
        if (!isnull)
        {
            bytea *cert_raw = DatumGetByteaPP(cert);
            cert_guid = (bytea *) SPI_palloc(VARSIZE_ANY(cert_raw));
            memcpy(cert_guid, cert_raw, VARSIZE_ANY(cert_raw));
        }
    }
 
    {
        std::ostringstream sql;
        sql << "SELECT instance_id, chain_id, last_sequence_id, last_creation_time, encode(last_hash, 'hex') "
            << "FROM \"SYS\".dbms_blockchain_chains WHERE table_id = " << table.table_id
            << " AND last_sequence_id > 0 ORDER BY instance_id, chain_id";
        rc = SPI_execute(sql.str().c_str(), true, 0);
        if (rc != SPI_OK_SELECT)
            ereport(ERROR, (errmsg("could not build blockchain digest anchor")));
 
        for (uint64 i = 0; i < SPI_processed; ++i)
        {
            if (i > 0)
                rows_json += ",";
            bool isnull = false;
            HeapTuple row = SPI_tuptable->vals[i];
            TupleDesc desc = SPI_tuptable->tupdesc;
            rows_json += "{";
            rows_json += "\"instance_id\":" + std::to_string(DatumGetInt32(SPI_getbinval(row, desc, 1, &isnull)));
            rows_json += ",\"chain_id\":" + std::to_string(DatumGetInt32(SPI_getbinval(row, desc, 2, &isnull)));
            rows_json += ",\"sequence_id\":" + std::to_string(DatumGetInt64(SPI_getbinval(row, desc, 3, &isnull)));
            rows_json += ",\"creation_time\":\"";
            Datum ts = SPI_getbinval(row, desc, 4, &isnull);
            rows_json += isnull ? "" : json_escape(timestamptz_to_str(DatumGetTimestampTz(ts)));
            rows_json += "\",\"hash\":\"";
            Datum hash_hex = SPI_getbinval(row, desc, 5, &isnull);
            if (!isnull)
                rows_json += json_escape(text_to_string(DatumGetTextPP(hash_hex)));
            rows_json += "\"}";
        }
    }
    rows_json += "]";
 
    {
        std::string payload = "{\"schema_name\":\"" + json_escape(schema_name) + "\",\"table_name\":\"" +
                              json_escape(table_name) + "\",\"table_oid\":\"" + std::to_string(relid) +
                              "\",\"rows\":" + rows_json + "}";
        signed_bytes = bytea_from_bytes(payload);
        signature = make_signature_placeholder(signed_bytes, cert_guid, signature_algo);
        signed_bytes_hash = hash_sha512(signed_bytes);
    }
 
    {
        Oid argtypes[5] = {INT8OID, BYTEAOID, BYTEAOID, BYTEAOID, INT4OID};
        Datum args[5] = {
            Int64GetDatum(table.table_id),
            PointerGetDatum(signed_bytes),
            PointerGetDatum(signature),
            PointerGetDatum(cert_guid),
            Int32GetDatum(signature_algo)};
        char argnulls[5] = {' ', ' ', ' ', cert_guid ? ' ' : 'n', ' '};
        int insert_rc = SPI_execute_with_args(
            "INSERT INTO \"SYS\".dbms_blockchain_digests(table_id, signed_bytes, signature, certificate_guid, signature_algo) "
            "VALUES ($1, $2, $3, $4, $5) RETURNING digest_id",
            5, argtypes, args, argnulls, false, 1);
        if (insert_rc != SPI_OK_INSERT_RETURNING || SPI_processed != 1)
            ereport(ERROR, (errmsg("could not store blockchain digest anchor")));
 
        bool isnull = false;
        digest_id = DatumGetInt64(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull));
    }
 
    {
        int lock_rc = SPI_execute("LOCK TABLE \"SYS\".dbms_blockchain_anchors IN EXCLUSIVE MODE", false, 0);
        if (lock_rc != SPI_OK_UTILITY)
            ereport(ERROR, (errmsg("could not lock blockchain anchors")));
 
        Oid argtypes[1] = {INT8OID};
        Datum args[1] = {Int64GetDatum(table.table_id)};
        char argnulls[1] = {' '};
        int select_rc = SPI_execute_with_args(
            "SELECT anchor_hash FROM \"SYS\".dbms_blockchain_anchors "
            "WHERE table_id = $1 ORDER BY anchor_id DESC LIMIT 1",
            1, argtypes, args, argnulls, true, 1);
        if (select_rc != SPI_OK_SELECT)
            ereport(ERROR, (errmsg("could not read previous blockchain anchor")));
        if (SPI_processed == 1)
        {
            bool isnull = false;
            Datum previous = SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull);
            if (!isnull)
            {
                bytea *previous_raw = DatumGetByteaPP(previous);
                previous_anchor_hash = (bytea *) SPI_palloc(VARSIZE_ANY(previous_raw));
                memcpy(previous_anchor_hash, previous_raw, VARSIZE_ANY(previous_raw));
            }
        }
    }
 
    anchor_body = "{\"event\":\"BLOCKCHAIN_DIGEST_ANCHOR\"";
    anchor_body += ",\"version\":\"" RUDB_DBMS_BLOCKCHAIN_TABLE_VERSION "\"";
    anchor_body += ",\"schema_name\":\"" + json_escape(schema_name) + "\"";
    anchor_body += ",\"table_name\":\"" + json_escape(table_name) + "\"";
    anchor_body += ",\"table_oid\":\"" + std::to_string(relid) + "\"";
    anchor_body += ",\"signature_algo\":" + std::to_string(signature_algo);
    anchor_body += ",\"certificate_guid_hex\":\"" + bytea_to_hex(cert_guid) + "\"";
    anchor_body += ",\"previous_anchor_hash_hex\":\"" + bytea_to_hex(previous_anchor_hash) + "\"";
    anchor_body += ",\"signed_bytes_sha512\":\"" + bytea_to_hex(signed_bytes_hash) + "\"";
    anchor_body += ",\"signed_bytes_hex\":\"" + bytea_to_hex(signed_bytes) + "\"";
    anchor_body += ",\"signature_hex\":\"" + bytea_to_hex(signature) + "\"";
    anchor_body += ",\"rows\":" + rows_json;
    anchor_body += "}";
 
    anchor_hash = hash_sha512(bytea_from_bytes(anchor_body));
    anchor_json = anchor_body.substr(0, anchor_body.size() - 1);
    anchor_json += ",\"anchor_hash\":\"" + bytea_to_hex(anchor_hash) + "\"}";
 
    ereport(LOG, (errmsg("BLOCKCHAIN_DIGEST_ANCHOR: %s", anchor_json.c_str())));
 
    result = jsonb_from_string(anchor_json);
 
    {
        Oid argtypes[5] = {INT8OID, INT8OID, BYTEAOID, BYTEAOID, JSONBOID};
        Datum args[5] = {
            Int64GetDatum(table.table_id),
            Int64GetDatum(digest_id),
            PointerGetDatum(previous_anchor_hash),
            PointerGetDatum(anchor_hash),
            result};
        char argnulls[5] = {' ', ' ', previous_anchor_hash ? ' ' : 'n', ' ', ' '};
        int anchor_rc = SPI_execute_with_args(
            "INSERT INTO \"SYS\".dbms_blockchain_anchors"
            "(table_id, digest_id, previous_anchor_hash, anchor_hash, anchor_payload) "
            "VALUES ($1, $2, $3, $4, $5)",
            5, argtypes, args, argnulls, false, 0);
        if (anchor_rc != SPI_OK_INSERT)
            ereport(ERROR, (errmsg("could not store blockchain anchor")));
    }
 
    spi_finish_or_error();
    PG_RETURN_DATUM(result);
}
 
Datum
dbms_blockchain_table_verify_table_blockchain(PG_FUNCTION_ARGS)
{
    bytea *latest = PG_GETARG_BYTEA_PP(0);
    bytea *previous = PG_GETARG_BYTEA_PP(1);
    int64 verified = 0;
 
    spi_connect_or_error();
 
    Oid argtypes[2] = {BYTEAOID, BYTEAOID};
    Datum args[2] = {PointerGetDatum(latest), PointerGetDatum(previous)};
    char nulls[2] = {' ', ' '};
    int rc = SPI_execute_with_args(
        "SELECT lt.schema_name, lt.table_name, p.created_at, l.created_at "
        "FROM \"SYS\".dbms_blockchain_digests l "
        "JOIN \"SYS\".dbms_blockchain_digests p ON p.signed_bytes = $2 "
        "JOIN \"SYS\".dbms_blockchain_tables lt ON lt.table_id = l.table_id "
        "JOIN \"SYS\".dbms_blockchain_tables pt ON pt.table_id = p.table_id "
        "WHERE l.signed_bytes = $1 AND lt.table_id = pt.table_id",
        2, argtypes, args, nulls, true, 1);
 
    if (rc != SPI_OK_SELECT || SPI_processed != 1)
        ereport(ERROR, (errmsg("blockchain digests are not known or belong to different tables")));
 
    {
        bool isnull = false;
        HeapTuple row = SPI_tuptable->vals[0];
        TupleDesc desc = SPI_tuptable->tupdesc;
        std::string schema_name = text_to_string(DatumGetTextPP(SPI_getbinval(row, desc, 1, &isnull)));
        std::string table_name = text_to_string(DatumGetTextPP(SPI_getbinval(row, desc, 2, &isnull)));
        TimestampTz low_ts = DatumGetTimestampTz(SPI_getbinval(row, desc, 3, &isnull));
        TimestampTz high_ts = DatumGetTimestampTz(SPI_getbinval(row, desc, 4, &isnull));
        std::ostringstream sql;
        sql << "SELECT pg_catalog.dbms_blockchain_table_verify_rows("
            << quote_literal_cstr(schema_name.c_str()) << ", "
            << quote_literal_cstr(table_name.c_str()) << ", '"
            << timestamptz_to_str(low_ts) << "'::timestamptz, '"
            << timestamptz_to_str(high_ts) << "'::timestamptz, NULL, NULL, true)";
        rc = SPI_execute(sql.str().c_str(), false, 1);
        if (rc != SPI_OK_SELECT || SPI_processed != 1)
            ereport(ERROR, (errmsg("could not verify blockchain table between digests")));
        verified = DatumGetInt64(SPI_getbinval(SPI_tuptable->vals[0], SPI_tuptable->tupdesc, 1, &isnull));
    }
 
    spi_finish_or_error();
    PG_RETURN_INT64(verified);
}
 
} // extern "C"