syntax = "proto3";

package arpc;

// Omen (formerly aRPC v3) streams transactions, entries, slot status, and
// control messages over a single bidirectional Subscribe stream. Docs:
// https://docs.corvus-labs.io/omen. The package name is `arpc`, the same as the
// legacy aRPC proto: never compile both into one build. Identity encoding only
// — no gzip/zstd.
service aRPC {
  rpc Subscribe(stream ClientMessage) returns (stream ServerMessage);
}

message ClientMessage {
  oneof msg {
    Resume resume = 1; // optional; when present, MUST be the first message
    SubscriptionRequest subscribe = 2; // add or replace a sub_id
    Unsubscribe unsubscribe = 3;
    Ping ping = 4;
    ConnectionConfig config = 5;
  }
}

// Replay retained frames from `from_slot` onward, then join live. A slot below
// the retention window is rejected with OUT_OF_RANGE; the client de-dups the
// replayed tail on the (slot, batch_index, entry_index, tx_index) key.
message Resume {
  uint64 from_slot = 1;
}

enum OnLag {
  ON_LAG_CLOSE = 0; // close the stream with DATA_LOSS "lagged"
  ON_LAG_SKIP_TO_LIVE = 1; // jump the cursor to head and emit a GapNotice
  ON_LAG_CONFLATE = 2; // slot-status subs keep the latest per slot; data subs behave as SKIP_TO_LIVE
}

message Unsubscribe {
  uint32 sub_id = 1; // the sub_id (0..63) to tear down
}

message Ping {
  uint64 id = 1; // echoed back in Pong for RTT measurement
}

message ConnectionConfig {
  OnLag on_lag = 1; // connection-wide lag policy; may precede subscribes
}

message SubscriptionRequest {
  uint32 sub_id = 1; // client-chosen, 0..63
  oneof kind {
    TransactionSubscription transactions = 2;
    EntrySubscription entries = 3;
    SlotSubscription slots = 4;
  }
  DataPolicy policy = 5;
}

// Selects which provenance classes of a frame a subscription receives.
message DataPolicy {
  bool exclude_recovered = 1; // drop Reed-Solomon-recovered frames
  bool exclude_repaired = 2; // drop turbine-repaired frames
  bool include_unverified = 3; // no effect: every frame is verified before it is sent
}

message TransactionSubscription {
  repeated bytes account_include = 1; // raw 32-byte keys; matched over static + LUT-resolved keys
  repeated bytes account_exclude = 2;
  repeated bytes account_required = 3;
  bool exclude_votes = 4;
  TransactionEncoding encoding = 5;
  // Compressed alternative to account_include: REPLACES the include predicate
  // with a probabilistic membership probe (no false negatives, ~1e-6 false
  // positives at 16-bit fingerprints; the client drops false positives
  // locally). Combining it with a non-empty account_include is rejected with
  // ACK_REASON_CUCKOO_FILTER_INVALID; account_exclude / account_required /
  // exclude_votes / encoding / DataPolicy still apply (AND) unchanged.
  //
  // Failure surfaces — where to look for the error:
  //   * SubscribeAck (stream stays open): bad geometry / algorithm / bucket
  //     count, combined with account_include
  //     (ACK_REASON_CUCKOO_FILTER_INVALID), or no cuckoo filter capacity
  //     left (ACK_REASON_CUCKOO_FILTER_LIMIT — retry after an unsubscribe
  //     frees one).
  //   * Stream-fatal gRPC status (no SubscribeAck follows): empty data,
  //     data above the server's size limit, or a wrong wire type on this
  //     field close the whole stream with INVALID_ARGUMENT.
  //   * Retryable gRPC status: a message larger than the normal bound but
  //     within the server's big-message limit is admitted only when capacity
  //     allows; otherwise the stream is closed with RESOURCE_EXHAUSTED —
  //     transient, retry with backoff.
  CuckooFilter cuckoo_account_include = 6;
}

enum TransactionEncoding {
  TRANSACTION_ENCODING_BINARY = 0; // exact wire bytes (default)
  TRANSACTION_ENCODING_DECODED = 1; // parsed Transaction with LUT-resolved addresses
}

// A serialized cuckoo filter over raw 32-byte account keys. Each bucket is 8
// bytes: 4 little-endian 16-bit fingerprint lanes (fingerprint 0 means an
// empty lane). The server derives the bucket count as floor(len(data) / 8),
// which must be a nonzero power of two; trailing bytes past the last whole
// bucket are ignored.
message CuckooFilter {
  // Bucket bytes. Empty or above the server's size limit is STREAM-FATAL
  // (gRPC INVALID_ARGUMENT — the enclosing Subscribe stream closes; no
  // SubscribeAck is sent); invalid geometry within the size limit is acked
  // with ACK_REASON_CUCKOO_FILTER_INVALID instead. See
  // TransactionSubscription.cuckoo_account_include for the full failure
  // split.
  bytes data = 1;
  uint32 bucket_count = 2; // advisory only; never trusted (derived from len(data))
  uint32 entries_per_bucket = 3; // 4, or 0 = unset (treated as 4)
  uint32 fingerprint_bits = 4; // 16, or 0 = unset (treated as 16)
  // SipHash k0; k1 = rotl64(hash_seed, 32). ABSENT decodes as 0 (a valid
  // seed), NOT the conventional client default 0x796c6c7773746e21 — clients
  // using that default must send it explicitly.
  uint64 hash_seed = 5;
  CuckooHashAlgorithm hash_algorithm = 6;
}

enum CuckooHashAlgorithm {
  CUCKOO_HASH_ALGORITHM_SIP_HASH_2_4 = 0; // the only supported algorithm
}

message EntrySubscription {
  EntryMetadataFilter metadata = 1; // tx/signature count ranges + tick gating
}

message EntryMetadataFilter {
  optional uint32 min_transaction_count = 1;
  optional uint32 max_transaction_count = 2;
  optional uint32 min_signature_count = 3;
  optional uint32 max_signature_count = 4;
  optional bool include_tick_entries = 5;
  optional bool include_non_tick_entries = 6;
}

message SlotSubscription {
  bool include_dead = 1;
  bool include_complete = 2;
  bool include_first_shred = 3;
}

// Fields 1, 16 and 17 are specific to your connection; fields 2..15 describe
// the frame itself and are the same for every subscriber that receives it.
message ServerMessage {
  uint64 matched_subs = 1; // bitmask of this connection's sub_ids that matched
  bool replayed = 16; // this delivery was served from replay
  // Per-connection delivery counter, +1 per frame on this connection.
  // Gap-free by contract — any gap the client observes is a transport bug.
  fixed64 conn_seq = 17;

  // Server-global monotonic frame id. NOT gap-free for a filtered stream — a
  // de-dup key only, never for gap detection.
  fixed64 seq = 2;
  // Unix time in nanoseconds at which the data in this frame was first
  // received; control-only frames carry the server's time.
  fixed64 created_at_ns = 3;
  uint32 provenance = 4; // bit0 PARTIAL_RUN, bit1 RECOVERED, bit2 REPAIRED, bit3 UNVERIFIED; bits 8..31 reserved
  oneof payload {
    BinaryTransaction binary_transaction = 5;
    DecodedTransaction decoded_transaction = 6;
    Entry entry = 7;
    SlotStatusUpdate slot = 8;
    SlotRetract retract = 9;
    Pong pong = 10;
    SubscribeAck ack = 11;
    StreamError error = 12;
    Heartbeat heartbeat = 13;
    ReplayComplete replay_done = 14;
    GapNotice gap = 15;
  }
}

enum SlotStatus {
  SLOT_STATUS_ALIVE = 0;
  SLOT_STATUS_FIRST_SHRED = 1;
  SLOT_STATUS_COMPLETE = 2;
  SLOT_STATUS_DEAD = 3;
  reserved 8, 9; // reserved for consensus statuses; this version is pre-consensus only
}

// A transaction as exact wire bytes plus its primary signature and position.
message BinaryTransaction {
  uint64 slot = 1;
  uint32 batch_index = 2;
  uint32 entry_index = 3;
  uint32 tx_index = 4;
  bytes signature = 5; // 64-byte primary signature (raw, no base58)
  bytes transaction = 6; // exact wire bytes of the transaction
}

// A fully parsed transaction: the Transaction/Message shape plus LUT-resolved
// loaded address lists, is_vote, and fee_payer.
message DecodedTransaction {
  uint64 slot = 1;
  uint32 batch_index = 2;
  uint32 entry_index = 3;
  uint32 tx_index = 4;
  bytes signature = 5;
  Transaction transaction = 6;
  bool lut_miss = 7; // at least one LUT-referenced key was unresolved
}

message Transaction {
  repeated bytes signatures = 1;
  Message message = 2;
  bool is_vote = 3;
  bytes fee_payer = 4;
}

message Message {
  MessageHeader header = 1;
  repeated bytes account_keys = 2;
  bytes recent_blockhash = 3;
  repeated CompiledInstruction instructions = 4;
  repeated MessageAddressTableLookup address_table_lookups = 5;
  repeated bytes loaded_writable_addresses = 6; // LUT-resolved
  repeated bytes loaded_readonly_addresses = 7; // LUT-resolved
  TransactionVersion transaction_version = 8;
  TransactionConfig transaction_config = 9; // present only for v1
}

message MessageHeader {
  uint32 num_required_signatures = 1;
  uint32 num_readonly_signed_accounts = 2;
  uint32 num_readonly_unsigned_accounts = 3;
}

message CompiledInstruction {
  uint32 program_id_index = 1;
  bytes accounts = 2;
  bytes data = 3;
}

message MessageAddressTableLookup {
  bytes account_key = 1;
  bytes writable_indexes = 2;
  bytes readonly_indexes = 3;
}

message Entry {
  uint64 slot = 1;
  uint32 batch_index = 2;
  uint32 entry_index = 3;
  bytes data = 4; // bincode entry bytes (exact leader-signed bytes)
  uint32 tx_count = 5;
  uint32 sig_count = 6;
  bool tick_only = 7;
  bool is_last_in_slot = 8;
}

message SlotStatusUpdate {
  uint64 slot = 1;
  SlotStatus status = 2;
  bytes leader = 3; // 32-byte leader pubkey; empty when unknown
}

// Discard everything previously delivered for this slot; `reason` distinguishes
// a dead slot from equivocation or a verification failure.
message SlotRetract {
  uint64 slot = 1;
  RetractReason reason = 2;
}

enum RetractReason {
  RETRACT_REASON_UNSPECIFIED = 0;
  RETRACT_REASON_DEAD = 1; // the slot was declared dead
  RETRACT_REASON_EQUIVOCATION = 2; // the leader produced a conflicting version of this slot, and this one lost
  RETRACT_REASON_VERIFY_FAILED = 3; // leader signature verification failed
}

message Pong {
  uint64 id = 1; // echoes Ping.id
}

message SubscribeAck {
  uint32 sub_id = 1;
  bool accepted = 2;
  AckReason reason = 3;
}

// Detail for a SubscribeAck. Normally set only when accepted = false;
// ACK_REASON_SUPERSEDED is the one reason that rides on an ACCEPTED ack —
// the request was admitted and then replaced by the client's own later
// request for the same sub_id, so it must not be treated as a failure.
// Admission limits are enforced at ack time.
enum AckReason {
  ACK_REASON_NONE = 0; // accepted, or no further detail
  ACK_REASON_INVALID_SUB_ID = 1; // sub_id > 63
  ACK_REASON_INVALID_FILTER = 2; // malformed filter (e.g. a key that is not 32 bytes)
  ACK_REASON_MAX_KEYS_PER_SUB = 3;
  ACK_REASON_MAX_KEYS_PER_CONN = 4;
  ACK_REASON_MAX_SUBS_PER_CONN = 5;
  ACK_REASON_FILTER_TOO_LARGE = 6; // the filter is too large for the server to accept - shrink the filter
  ACK_REASON_FILTER_TOO_BROAD = 7; // unfiltered subscription refused: firehose capacity is full
  reserved 8; // retired; never reused
  ACK_REASON_CUCKOO_FILTER_INVALID = 9; // bad geometry/algorithm/bucket count, or combined with account_include
  ACK_REASON_CUCKOO_FILTER_LIMIT = 10; // no cuckoo filter capacity left
  ACK_REASON_SERVER_RESOURCES = 11; // transient server capacity limit (not filter size) - retry with backoff
  ACK_REASON_SUPERSEDED = 12; // a later SubscriptionRequest for this sub_id replaced this one; not an error
}

message StreamError {
  ErrorCode code = 1;
  string message = 2;
  uint32 retry_after_ms = 3; // 0 = no retry hint
}

enum ErrorCode {
  ERROR_CODE_UNSPECIFIED = 0;
  ERROR_CODE_UNKNOWN = 1;
  ERROR_CODE_INVALID_FILTER = 2;
  ERROR_CODE_FILTER_TOO_COMPLEX = 3;
  ERROR_CODE_RATE_LIMITED = 4;
  ERROR_CODE_QUOTA_EXCEEDED = 5;
  ERROR_CODE_INTERNAL = 6;
  ERROR_CODE_UNAVAILABLE = 7;
  ERROR_CODE_SHUTTING_DOWN = 8; // the server is shutting down; carries a jittered retry_after_ms
  ERROR_CODE_FLOW_CONTROL_LIMITED = 9; // advisory: persistent client HTTP/2 window starvation
  ERROR_CODE_RESOURCE_EXHAUSTED = 10; // replay / broad-subscription admission control; carries retry_after_ms
  ERROR_CODE_OUT_OF_RANGE = 11; // requested replay slot is older than retention
}

// Idle keepalive carrying the newest observed slot so idle clients see head progress.
message Heartbeat {
  uint64 slot = 1;
}

// Sent when a Resume replay reaches the live head.
message ReplayComplete {
  fixed64 live_seq = 1; // head frame id at the moment the stream joined live
}

// Emitted under SKIP_TO_LIVE / CONFLATE to mark a skipped seq range.
message GapNotice {
  fixed64 from_seq = 1; // last seq delivered before the gap
  fixed64 to_seq = 2; // first seq delivered after the jump to live
}

enum TransactionVersion {
  TRANSACTION_VERSION_LEGACY = 0;
  TRANSACTION_VERSION_V0 = 1;
  TRANSACTION_VERSION_V1 = 2;
}

// The mask preserves presence even when a configured scalar is zero.
message TransactionConfig {
  uint32 mask = 1;
  uint64 priority_fee = 2;
  uint32 compute_unit_limit = 3;
  uint32 loaded_accounts_data_size_limit = 4;
  uint32 heap_size = 5;
}
