-- Note: All timestamps inside this DB have to be in UTC+0
-- Otherwise u can travel back to future
SET TIME ZONE 'UTC';

CREATE TABLE blocks (
    id          BIGSERIAL PRIMARY KEY,
    -- SHA512 sum of all hashes inside the block + prev_hash
    -- 32 bytes long
    hash        BYTEA     UNIQUE,
    -- NULL only on the first block
    prev_hash   BYTEA     UNIQUE,
    started_at  TIMESTAMP NOT NULL,
    finished_at TIMESTAMP,
)

CREATE TABLE IF NOT EXISTS transactions (
    -- SHA512 -- 32 bytes long
    hash     BYTEA PRIMARY KEY,
    block_id BIGINT REFERENCES blocks(id) NOT NULL,

    -- ED25519 32 bytes long
    sender_public_key   BYTEA NOT NULL,
    receiver_public_key BYTEA NOT NULL,

    -- Rewards doesn't decrease sender's balance
    -- but generate additional crypto inside the system.
    -- Not each sender_public_key should be able to send rewards.
    is_reward BOOLEAN NOT NULL,

    amount        DOUBLE PRECISION NOT NULL,
    amount_burned DOUBLE PRECISION NOT NULL,
    message       VARCHAR,

    -- When sign is decrypted with the sender's
    -- public key we should get the created_at
    -- time in unix format
    signature BYTEA NOT NULL,
    -- Time provided by the client
    created_at TIMESTAMP,
    -- Time when transaction was added to the server
    added_at   TIMESTAMP SET DEFAULT CURRENT TIMESTAMP,

    -- Prevent block duplicates
    UNIQUE(sendrt_public_key, signature)

    -- NOTE: Will be extended with smart contracts data
);
CREATE INDEX idx_blocks_hash              ON blocks (hash);
CREATE INDEX idx_blocks_prev_hash         ON prev_hash (prev_hash);
CREATE INDEX idx_transactions_block_id    ON transactions (block_id);
CREATE INDEX idx_transactions_sender_pk   ON transactions (sender_public_key);
CREATE INDEX idx_transactions_receiver_pk ON transactions (receiver_public_key);