#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")));
|
}
|
|
/*
|
* heap_modify_tuple_by_cols() allocates in the current SPI procedure
|
* context. Copy the trigger result into SPI's saved (upper executor)
|
* context before SPI_finish() destroys the procedure context.
|
*/
|
HeapTuple result_tuple = SPI_copytuple(tuple);
|
if (result_tuple == nullptr)
|
ereport(ERROR, (errmsg("could not copy blockchain trigger tuple")));
|
|
spi_finish_or_error();
|
return PointerGetDatum(result_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);
|
|
/* Return the composite from the upper executor context, not SPI's
|
* procedure context, which is destroyed by SPI_finish(). */
|
HeapTuple result_tuple = heap_form_tuple(out_desc, values, nulls);
|
result_tuple = SPI_copytuple(result_tuple);
|
if (result_tuple == nullptr)
|
ereport(ERROR, (errmsg("could not copy blockchain digest result")));
|
|
spi_finish_or_error();
|
PG_RETURN_DATUM(HeapTupleGetDatum(result_tuple));
|
}
|
|
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")));
|
}
|
|
/* jsonb is pass-by-reference; transfer it to SPI's saved upper
|
* executor context before disconnecting. */
|
result = SPI_datumTransfer(result, false, -1);
|
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"
|