syntax = "proto3";

import "google/protobuf/any.proto";
import "core/Discover.proto";
import "core/contract/common.proto";

package protocol;


option java_package = "org.tron.protos"; //Specify the name of the package that generated the Java file
option java_outer_classname = "Protocol"; //Specify the class name of the generated Java file
option go_package = "github.com/tronprotocol/grpc-gateway/core";

enum AccountType {
  Normal = 0;
  AssetIssue = 1;
  Contract = 2;
}

// AccountId, (name, address) use name, (null, address) use address, (name, null) use name,
message AccountId {
  bytes name = 1;
  bytes address = 2;
}

// vote message
message Vote {
  // the super rep address
  bytes vote_address = 1;
  // the vote num to this super rep.
  int64 vote_count = 2;
}

// Proposal
message Proposal {
  int64 proposal_id = 1;
  bytes proposer_address = 2;
  map<int64, int64> parameters = 3;
  int64 expiration_time = 4;
  int64 create_time = 5;
  repeated bytes approvals = 6;
  enum State {
    PENDING = 0;
    DISAPPROVED = 1;
    APPROVED = 2;
    CANCELED = 3;
  }
  State state = 7;
}

// Exchange
message Exchange {
  int64 exchange_id = 1;
  bytes creator_address = 2;
  int64 create_time = 3;
  bytes first_token_id = 6;
  int64 first_token_balance = 7;
  bytes second_token_id = 8;
  int64 second_token_balance = 9;
}

// market
message MarketOrder {
    bytes order_id = 1;
    bytes owner_address = 2;
    int64 create_time = 3;
    bytes sell_token_id = 4;
    int64 sell_token_quantity = 5;
    bytes buy_token_id = 6;
    int64 buy_token_quantity = 7; // min to receive
    int64 sell_token_quantity_remain = 9;
    // When state != ACTIVE and sell_token_quantity_return !=0,
    //it means that some sell tokens are returned to the account due to insufficient remaining amount
    int64 sell_token_quantity_return = 10;

    enum State {
      ACTIVE = 0;
      INACTIVE = 1;
      CANCELED = 2;
    }
    State state = 11;

    bytes prev = 12;
    bytes next = 13;
}

message MarketOrderList {
    repeated MarketOrder orders = 1;
}

message MarketOrderPairList {
  repeated MarketOrderPair orderPair = 1;
}

message MarketOrderPair{
    bytes sell_token_id = 1;
    bytes buy_token_id = 2;
}

message MarketAccountOrder {
  bytes owner_address = 1;
  repeated bytes orders = 2; // order_id list
  int64 count = 3; // active count
  int64 total_count = 4;
}

message MarketPrice {
  int64 sell_token_quantity = 1;
  int64 buy_token_quantity = 2;
}

message MarketPriceList {
  bytes sell_token_id = 1;
  bytes buy_token_id = 2;
  repeated MarketPrice prices = 3;
}

message MarketOrderIdList {
  bytes head = 1;
  bytes tail = 2;
}

message ChainParameters {
  repeated ChainParameter chainParameter = 1;
  message ChainParameter {
    string key = 1;
    int64 value = 2;
  }
}

/* Account */
message Account {
  /* frozen balance */
  message Frozen {
    int64 frozen_balance = 1; // the frozen trx balance
    int64 expire_time = 2; // the expire time
  }
  // account nick name
  bytes account_name = 1;
  AccountType type = 2;
  // the create address
  bytes address = 3;
  // the trx balance
  int64 balance = 4;
  // the votes
  repeated Vote votes = 5;
  // the other asset owned by this account
  map<string, int64> asset = 6;

  // the other asset owned by this account，key is assetId
  map<string, int64> assetV2 = 56;

  // the frozen balance for bandwidth
  repeated Frozen frozen = 7;
  // bandwidth, get from frozen
  int64 net_usage = 8;
  //Frozen balance provided by other accounts to this account
  int64 acquired_delegated_frozen_balance_for_bandwidth = 41;
  //Freeze and provide balances to other accounts
  int64 delegated_frozen_balance_for_bandwidth = 42;

  int64 old_tron_power = 46;
  Frozen tron_power = 47;

  bool asset_optimized = 60;

  // this account create time
  int64 create_time = 0x09;
  // this last operation time, including transfer, voting and so on. //FIXME fix grammar
  int64 latest_opration_time = 10;
  // witness block producing allowance
  int64 allowance = 0x0B;
  // last withdraw time
  int64 latest_withdraw_time = 0x0C;
  // not used so far
  bytes code = 13;
  bool is_witness = 14;
  bool is_committee = 15;
  // frozen asset(for asset issuer)
  repeated Frozen frozen_supply = 16;
  // asset_issued_name
  bytes asset_issued_name = 17;
  bytes asset_issued_ID = 57;
  map<string, int64> latest_asset_operation_time = 18;
  map<string, int64> latest_asset_operation_timeV2 = 58;
  int64 free_net_usage = 19;
  map<string, int64> free_asset_net_usage = 20;
  map<string, int64> free_asset_net_usageV2 = 59;
  int64 latest_consume_time = 21;
  int64 latest_consume_free_time = 22;

  // the identity of this account, case insensitive
  bytes account_id = 23;

  int64 net_window_size = 24;
  bool net_window_optimized = 25;

  message AccountResource {
    // energy resource, get from frozen
    int64 energy_usage = 1;
    // the frozen balance for energy
    Frozen frozen_balance_for_energy = 2;
    int64 latest_consume_time_for_energy = 3;

    //Frozen balance provided by other accounts to this account
    int64 acquired_delegated_frozen_balance_for_energy = 4;
    //Frozen balances provided to other accounts
    int64 delegated_frozen_balance_for_energy = 5;

    // storage resource, get from market
    int64 storage_limit = 6;
    int64 storage_usage = 7;
    int64 latest_exchange_storage_time = 8;

    int64 energy_window_size = 9;

    int64 delegated_frozenV2_balance_for_energy = 10;
    int64 acquired_delegated_frozenV2_balance_for_energy = 11;
    bool energy_window_optimized = 12;
  }
  AccountResource account_resource = 26;
  bytes codeHash = 30;
  Permission owner_permission = 31;
  Permission witness_permission = 32;
  repeated Permission active_permission = 33;

  message FreezeV2 {
    ResourceCode type = 1;
    int64 amount = 2;
  }
  message UnFreezeV2 {
    ResourceCode type = 1;
    int64 unfreeze_amount = 3;
    int64 unfreeze_expire_time = 4;
  }
  repeated FreezeV2 frozenV2 = 34;
  repeated UnFreezeV2 unfrozenV2 = 35;

  int64 delegated_frozenV2_balance_for_bandwidth = 36;
  int64 acquired_delegated_frozenV2_balance_for_bandwidth = 37;
}

message Key {
  bytes address = 1;
  int64 weight = 2;
}

message DelegatedResource {
  bytes from = 1;
  bytes to = 2;
  int64 frozen_balance_for_bandwidth = 3;
  int64 frozen_balance_for_energy = 4;
  int64 expire_time_for_bandwidth = 5;
  int64 expire_time_for_energy = 6;
}

message authority {
  AccountId account = 1;
  bytes permission_name = 2;
}

message Permission {
  enum PermissionType {
    Owner = 0;
    Witness = 1;
    Active = 2;
  }
  PermissionType type = 1;
  int32 id = 2; //Owner id=0, Witness id=1, Active id start by 2
  string permission_name = 3;
  int64 threshold = 4;
  int32 parent_id = 5;
  bytes operations = 6; //1 bit 1 contract
  repeated Key keys = 7;
}

// Witness
message Witness {
  bytes address = 1;
  int64 voteCount = 2;
  bytes pubKey = 3;
  string url = 4;
  int64 totalProduced = 5;
  int64 totalMissed = 6;
  int64 latestBlockNum = 7;
  int64 latestSlotNum = 8;
  bool isJobs = 9;
}

// Vote Change
message Votes {
  bytes address = 1;
  repeated Vote old_votes = 2;
  repeated Vote new_votes = 3;
}

// Transcation

message TXOutput {
  int64 value = 1;
  bytes pubKeyHash = 2;
}

message TXInput {
  message raw {
    bytes txID = 1;
    int64 vout = 2;
    bytes pubKey = 3;
  }
  raw raw_data = 1;
  bytes signature = 4;
}

message TXOutputs {
  repeated TXOutput outputs = 1;
}

message ResourceReceipt {
  int64 energy_usage = 1;
  int64 energy_fee = 2;
  int64 origin_energy_usage = 3;
  int64 energy_usage_total = 4;
  int64 net_usage = 5;
  int64 net_fee = 6;
  Transaction.Result.contractResult result = 7;
  int64 energy_penalty_total = 8;
}

message MarketOrderDetail {
  bytes makerOrderId = 1;
  bytes takerOrderId = 2;
  int64 fillSellQuantity = 3;
  int64 fillBuyQuantity = 4;
}

message Transaction {
  message Contract {
    enum ContractType {
      AccountCreateContract = 0;
      TransferContract = 1;
      TransferAssetContract = 2;
      VoteAssetContract = 3;
      VoteWitnessContract = 4;
      WitnessCreateContract = 5;
      AssetIssueContract = 6;
      WitnessUpdateContract = 8;
      ParticipateAssetIssueContract = 9;
      AccountUpdateContract = 10;
      FreezeBalanceContract = 11;
      UnfreezeBalanceContract = 12;
      WithdrawBalanceContract = 13;
      UnfreezeAssetContract = 14;
      UpdateAssetContract = 15;
      ProposalCreateContract = 16;
      ProposalApproveContract = 17;
      ProposalDeleteContract = 18;
      SetAccountIdContract = 19;
      CustomContract = 20;
      CreateSmartContract = 30;
      TriggerSmartContract = 31;
      GetContract = 32;
      UpdateSettingContract = 33;
      ExchangeCreateContract = 41;
      ExchangeInjectContract = 42;
      ExchangeWithdrawContract = 43;
      ExchangeTransactionContract = 44;
      UpdateEnergyLimitContract = 45;
      AccountPermissionUpdateContract = 46;
      ClearABIContract = 48;
      UpdateBrokerageContract = 49;
      ShieldedTransferContract = 51;
      MarketSellAssetContract = 52;
      MarketCancelOrderContract = 53;
      FreezeBalanceV2Contract = 54;
      UnfreezeBalanceV2Contract = 55;
      WithdrawExpireUnfreezeContract = 56;
      DelegateResourceContract = 57;
      UnDelegateResourceContract = 58;
      CancelAllUnfreezeV2Contract = 59;
    }
    ContractType type = 1;
    google.protobuf.Any parameter = 2;
    bytes provider = 3;
    bytes ContractName = 4;
    int32 Permission_id = 5;
  }

  message Result {
    enum code {
      SUCESS = 0;
      FAILED = 1;
    }
    enum contractResult {
      DEFAULT = 0;
      SUCCESS = 1;
      REVERT = 2;
      BAD_JUMP_DESTINATION = 3;
      OUT_OF_MEMORY = 4;
      PRECOMPILED_CONTRACT = 5;
      STACK_TOO_SMALL = 6;
      STACK_TOO_LARGE = 7;
      ILLEGAL_OPERATION = 8;
      STACK_OVERFLOW = 9;
      OUT_OF_ENERGY = 10;
      OUT_OF_TIME = 11;
      JVM_STACK_OVER_FLOW = 12;
      UNKNOWN = 13;
      TRANSFER_FAILED = 14;
      INVALID_CODE = 15;
    }
    int64 fee = 1;
    code ret = 2;
    contractResult contractRet = 3;

    string assetIssueID = 14;
    int64 withdraw_amount = 15;
    int64 unfreeze_amount = 16;
    int64 exchange_received_amount = 18;
    int64 exchange_inject_another_amount = 19;
    int64 exchange_withdraw_another_amount = 20;
    int64 exchange_id = 21;
    int64 shielded_transaction_fee = 22;


    bytes orderId = 25;
    repeated MarketOrderDetail orderDetails = 26;
    int64 withdraw_expire_amount = 27;
    map<string, int64> cancel_unfreezeV2_amount = 28;
  }

  message raw {
    bytes ref_block_bytes = 1;
    int64 ref_block_num = 3;
    bytes ref_block_hash = 4;
    int64 expiration = 8;
    repeated authority auths = 9;
    // data not used
    bytes data = 10;
    //only support size = 1,  repeated list here for extension
    repeated Contract contract = 11;
    // scripts not used
    bytes scripts = 12;
    int64 timestamp = 14;
    int64 fee_limit = 18;
  }

  raw raw_data = 1;
  // only support size = 1,  repeated list here for muti-sig extension
  repeated bytes signature = 2;
  repeated Result ret = 5;
}

message TransactionInfo {
  enum code {
    SUCESS = 0;
    FAILED = 1;
  }
  message Log {
    bytes address = 1;
    repeated bytes topics = 2;
    bytes data = 3;
  }
  bytes id = 1;
  int64 fee = 2;
  int64 blockNumber = 3;
  int64 blockTimeStamp = 4;
  repeated bytes contractResult = 5;
  bytes contract_address = 6;
  ResourceReceipt receipt = 7;
  repeated Log log = 8;
  code result = 9;
  bytes resMessage = 10;

  string assetIssueID = 14;
  int64 withdraw_amount = 15;
  int64 unfreeze_amount = 16;
  repeated InternalTransaction internal_transactions = 17;
  int64 exchange_received_amount = 18;
  int64 exchange_inject_another_amount = 19;
  int64 exchange_withdraw_another_amount = 20;
  int64 exchange_id = 21;
  int64 shielded_transaction_fee = 22;

  bytes orderId = 25;
  repeated MarketOrderDetail orderDetails = 26;
  int64 packingFee = 27;

  int64 withdraw_expire_amount = 28;
  map<string, int64> cancel_unfreezeV2_amount = 29;
}

message TransactionRet {
  int64 blockNumber = 1;
  int64 blockTimeStamp = 2;
  repeated TransactionInfo transactioninfo = 3;
}

message Transactions {
  repeated Transaction transactions = 1;
}

message BlockHeader {
  message raw {
    int64 timestamp = 1;
    bytes txTrieRoot = 2;
    bytes parentHash = 3;
    //bytes nonce = 5;
    //bytes difficulty = 6;
    int64 number = 7;
    int64 witness_id = 8;
    bytes witness_address = 9;
    int32 version = 10;
    bytes accountStateRoot = 11;
  }
  raw raw_data = 1;
  bytes witness_signature = 2;
}

// block
message Block {
  repeated Transaction transactions = 1;
  BlockHeader block_header = 2;
}

message ChainInventory {
  message BlockId {
    bytes hash = 1;
    int64 number = 2;
  }
  repeated BlockId ids = 1;
  int64 remain_num = 2;
}

// Inventory
message BlockInventory {
  enum Type {
    SYNC = 0;
    ADVTISE = 1;
    FETCH = 2;
  }

  message BlockId {
    bytes hash = 1;
    int64 number = 2;
  }
  repeated BlockId ids = 1;
  Type type = 2;
}

message Inventory {
  enum InventoryType {
    TRX = 0;
    BLOCK = 1;
  }
  InventoryType type = 1;
  repeated bytes ids = 2;
}

message Items {
  enum ItemType {
    ERR = 0;
    TRX = 1;
    BLOCK = 2;
    BLOCKHEADER = 3;
  }

  ItemType type = 1;
  repeated Block blocks = 2;
  repeated BlockHeader block_headers = 3;
  repeated Transaction transactions = 4;
}

// DynamicProperties
message DynamicProperties {
  int64 last_solidity_block_num = 1;
}

enum ReasonCode {
  REQUESTED = 0x00;
  BAD_PROTOCOL = 0x02;
  TOO_MANY_PEERS = 0x04;
  DUPLICATE_PEER = 0x05;
  INCOMPATIBLE_PROTOCOL = 0x06;
  RANDOM_ELIMINATION = 0x07;
  PEER_QUITING = 0x08;
  UNEXPECTED_IDENTITY = 0x09;
  LOCAL_IDENTITY = 0x0A;
  PING_TIMEOUT = 0x0B;
  USER_REASON = 0x10;
  RESET = 0x11;
  SYNC_FAIL = 0x12;
  FETCH_FAIL = 0x13;
  BAD_TX = 0x14;
  BAD_BLOCK = 0x15;
  FORKED = 0x16;
  UNLINKABLE = 0x17;
  INCOMPATIBLE_VERSION = 0x18;
  INCOMPATIBLE_CHAIN = 0x19;
  TIME_OUT = 0x20;
  CONNECT_FAIL = 0x21;
  TOO_MANY_PEERS_WITH_SAME_IP = 0x22;
  LIGHT_NODE_SYNC_FAIL = 0x23;
  BELOW_THAN_ME = 0X24;
  NOT_WITNESS = 0x25;
  NO_SUCH_MESSAGE = 0x26;
  UNKNOWN = 0xFF;
}

message DisconnectMessage {
  ReasonCode reason = 1;
}

message HelloMessage {
  message BlockId {
    bytes hash = 1;
    int64 number = 2;
  }

  Endpoint from = 1;
  int32 version = 2;
  int64 timestamp = 3;
  BlockId genesisBlockId = 4;
  BlockId solidBlockId = 5;
  BlockId headBlockId = 6;
  bytes address = 7;
  bytes signature = 8;
  int32 nodeType = 9;
  int64 lowestBlockNum = 10;
  bytes codeVersion = 11;
}

message InternalTransaction {
  // internalTransaction identity, the root InternalTransaction hash
  // should equals to root transaction id.
  bytes hash = 1;
  // the one send trx (TBD: or token) via function
  bytes caller_address = 2;
  // the one recieve trx (TBD: or token) via function
  bytes transferTo_address = 3;
  message CallValueInfo {
    // trx (TBD: or token) value
    int64 callValue = 1;
    // TBD: tokenName, trx should be empty
    string tokenId = 2;
  }
  repeated CallValueInfo callValueInfo = 4;
  bytes note = 5;
  bool rejected = 6;
  string extra = 7;
}

message DelegatedResourceAccountIndex {
  bytes account = 1;
  repeated bytes fromAccounts = 2;
  repeated bytes toAccounts = 3;
  int64 timestamp = 4;
}

message NodeInfo {
  int64 beginSyncNum = 1;
  string block = 2;
  string solidityBlock = 3;
  //connect information
  int32 currentConnectCount = 4;
  int32 activeConnectCount = 5;
  int32 passiveConnectCount = 6;
  int64 totalFlow = 7;
  repeated PeerInfo peerInfoList = 8;
  ConfigNodeInfo configNodeInfo = 9;
  MachineInfo machineInfo = 10;
  map<string, string> cheatWitnessInfoMap = 11;

  message PeerInfo {
    string lastSyncBlock = 1;
    int64 remainNum = 2;
    int64 lastBlockUpdateTime = 3;
    bool syncFlag = 4;
    int64 headBlockTimeWeBothHave = 5;
    bool needSyncFromPeer = 6;
    bool needSyncFromUs = 7;
    string host = 8;
    int32 port = 9;
    string nodeId = 10;
    int64 connectTime = 11;
    double avgLatency = 12;
    int32 syncToFetchSize = 13;
    int64 syncToFetchSizePeekNum = 14;
    int32 syncBlockRequestedSize = 15;
    int64 unFetchSynNum = 16;
    int32 blockInPorcSize = 17;
    string headBlockWeBothHave = 18;
    bool isActive = 19;
    int32 score = 20;
    int32 nodeCount = 21;
    int64 inFlow = 22;
    int32 disconnectTimes = 23;
    string localDisconnectReason = 24;
    string remoteDisconnectReason = 25;
  }

  message ConfigNodeInfo {
    string codeVersion = 1;
    string p2pVersion = 2;
    int32 listenPort = 3;
    bool discoverEnable = 4;
    int32 activeNodeSize = 5;
    int32 passiveNodeSize = 6;
    int32 sendNodeSize = 7;
    int32 maxConnectCount = 8;
    int32 sameIpMaxConnectCount = 9;
    int32 backupListenPort = 10;
    int32 backupMemberSize = 11;
    int32 backupPriority = 12;
    int32 dbVersion = 13;
    int32 minParticipationRate = 14;
    bool supportConstant = 15;
    double minTimeRatio = 16;
    double maxTimeRatio = 17;
    int64 allowCreationOfContracts = 18;
    int64 allowAdaptiveEnergy = 19;
  }

  message MachineInfo {
    int32 threadCount = 1;
    int32 deadLockThreadCount = 2;
    int32 cpuCount = 3;
    int64 totalMemory = 4;
    int64 freeMemory = 5;
    double cpuRate = 6;
    string javaVersion = 7;
    string osName = 8;
    int64 jvmTotalMemory = 9;
    int64 jvmFreeMemory = 10;
    double processCpuRate = 11;
    repeated MemoryDescInfo memoryDescInfoList = 12;
    repeated DeadLockThreadInfo deadLockThreadInfoList = 13;

    message MemoryDescInfo {
      string name = 1;
      int64 initSize = 2;
      int64 useSize = 3;
      int64 maxSize = 4;
      double useRate = 5;
    }

    message DeadLockThreadInfo {
      string name = 1;
      string lockName = 2;
      string lockOwner = 3;
      string state = 4;
      int64 blockTime = 5;
      int64 waitTime = 6;
      string stackTrace = 7;
    }
  }
}

message MetricsInfo {
  int64 interval = 1;
  NodeInfo node = 2;
  BlockChainInfo blockchain = 3;
  NetInfo net = 4;

  message NodeInfo {
    string ip = 1;
    int32 nodeType = 2;
    string version = 3;
    int32 backupStatus = 4;
  }

  message BlockChainInfo {
    int64 headBlockNum = 1;
    int64 headBlockTimestamp = 2;
    string headBlockHash = 3;
    int32 forkCount = 4;
    int32 failForkCount = 5;
    RateInfo blockProcessTime = 6;
    RateInfo tps = 7;
    int32 transactionCacheSize = 8;
    RateInfo missedTransaction = 9;
    repeated Witness witnesses = 10;
    int64 failProcessBlockNum = 11;
    string failProcessBlockReason = 12;
    repeated DupWitness dupWitness = 13;

    message Witness {
      string address = 1;
      int32 version = 2;
    }

    message DupWitness {
      string address = 1;
      int64 blockNum = 2;
      int32 count = 3;
    }
  }

  message RateInfo {
    int64 count = 1;
    double meanRate = 2;
    double oneMinuteRate = 3;
    double fiveMinuteRate = 4;
    double fifteenMinuteRate = 5;
  }

  message NetInfo {
    int32 errorProtoCount = 1;
    ApiInfo api = 2;
    int32 connectionCount = 3;
    int32 validConnectionCount = 4;
    RateInfo tcpInTraffic = 5;
    RateInfo tcpOutTraffic = 6;
    int32 disconnectionCount = 7;
    repeated DisconnectionDetailInfo disconnectionDetail = 8;
    RateInfo udpInTraffic = 9;
    RateInfo udpOutTraffic = 10;
    LatencyInfo latency = 11;

    message ApiInfo {
      RateInfo qps = 1;
      RateInfo failQps = 2;
      RateInfo outTraffic = 3;
      repeated ApiDetailInfo detail = 4;

      message ApiDetailInfo {
        string name = 1;
        RateInfo qps = 2;
        RateInfo failQps = 3;
        RateInfo outTraffic = 4;
      }
    }

    message DisconnectionDetailInfo {
      string reason = 1;
      int32 count = 2;
    }

    message LatencyInfo {
      int32 top99 = 1;
      int32 top95 = 2;
      int32 top75 = 3;
      int32 totalCount = 4;
      int32 delay1S = 5;
      int32 delay2S = 6;
      int32 delay3S = 7;
      repeated LatencyDetailInfo detail = 8;

      message LatencyDetailInfo {
        string witness = 1;
        int32 top99 = 2;
        int32 top95 = 3;
        int32 top75 = 4;
        int32 count = 5;
        int32 delay1S = 6;
        int32 delay2S = 7;
        int32 delay3S = 8;
      }
    }
  }
}

message PBFTMessage {
  enum MsgType {
    VIEW_CHANGE = 0;
    REQUEST = 1;
    PREPREPARE = 2;
    PREPARE = 3;
    COMMIT = 4;
  }
  enum DataType {
    BLOCK = 0;
    SRL = 1;
  }
  message Raw {
    MsgType msg_type = 1;
    DataType data_type = 2;
    int64 view_n = 3;
    int64 epoch = 4;
    bytes data = 5;
  }
  Raw raw_data = 1;
  bytes signature = 2;
}

message PBFTCommitResult {
  bytes data = 1;
  repeated bytes signature = 2;
}

message SRL {
  repeated bytes srAddress = 1;
}
