-- 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 (
    -- UNIX Timestamp
    -- But not just any timestamp, some timestamp
    id          BIGINT 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,
    finished_at TIMESTAMP,
)

CREATE TABLE IF NOT EXISTS transactions (
    -- SHA512 -- 64 bytes long
    hash     BYTEA(64) PRIMARY KEY,
    -- references block id
    -- but may be added before the block itself
    block_id BIGINT,

    -- ED25519 key -- 32 bytes long
    sender_public_key   BYTEA(32) NOT NULL,
    receiver_public_key BYTEA(32) 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(24) NOT NULL,
    -- Time provided by the client
    created_at    BIGINT NOT NULL,
    created_at_ns BIGINT NOT NULL,
    -- Time when transaction was added to the server
    added_at TIMESTAMP SET DEFAULT CURRENT TIMESTAMP,

    -- NOTE: Will be extended with smart contracts data
);

CREATE INDEX idx_blocks_hash              ON blocks (hash);
CREATE INDEX idx_blocks_prev_hash         ON blocks (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);