import "@fluencelabs/aqua-lib/builtin.aqua"


data Contact:
    peer_id: string
    addresses: []string

data Info:
    external_addresses: []string

service MyOp("op"):
    identity(u: u64)
    identity_string(s:string)

service MyOpBool("op"):
    identity(b: bool)

data Consensus:
  n: u32
  consensus_ts: u64
  consensus: bool
  support: u32
  err_str: string

data Oracle:
  n: u32
  avg: f64
  err_str: string

service TSOracle("service-id"):
  ts_frequency(timestamps: []u64, tolerance: u32, threshold: f64, err_value:u64) -> Consensus

func ts_oracle_with_consensus(tolerance: u32, threshold: f64, err_value:u64, node:string, oracle_service_id:string)-> Consensus, []string, u32:
  rtt  = 1000 -- in ms
  res: *u64
  msg = "timeout"
  dead_peers: *string
  on node:
    k <- Op.string_to_b58(node)
    nodes <- Kademlia.neighborhood(k, nil, nil)
    for n <- nodes par:
        status: *string
        on n:
            res <- Peer.timestamp_ms()
            status <<- "success"
        par status <- Peer.timeout(rtt, msg)
        if status! != "success":
          res <<- err_value
          dead_peers <<- n
    
    join res[Op.array_length(nodes) - Op.array_length(dead_peers) -1]
  
    TSOracle oracle_service_id
    consensus <- TSOracle.ts_frequency(res, tolerance, threshold, err_value)

  <- consensus, dead_peers, Op.array_length(nodes) - Op.array_length(dead_peers)
