create or replace function chat.pack(p_bits bit varying) returns bytea language sql immutable strict as $$ select substring(varbit_send(p_bits) from 5) $$; create or replace function chat.dot(p_h bit varying[], p_v bit varying) returns bit varying language sql immutable strict as $$ select string_agg((bit_count(bits & p_v) % 2)::text, '' order by ord)::bit varying from unnest(p_h) with ordinality as rows(bits, ord) $$; create or replace function chat.permute(p_v bit varying, p_order integer[]) returns bit varying language sql immutable strict as $$ select string_agg(get_bit(p_v, pos)::text, '' order by ord)::bit varying from unnest(p_order) with ordinality as positions(pos, ord) $$; create or replace function chat.hash(p_text text) returns text language sql immutable strict as $$ select encode(digest(p_text, 'sha256'), 'hex') $$; create or replace function chat.challenge() returns integer language plpgsql volatile as $$ declare v integer; begin loop v := get_byte(gen_random_bytes(1), 0); exit when v < 252; end loop; return v % 3; end; $$; create or replace function chat.make_parameters() returns jsonb language plpgsql volatile as $$ declare v_n integer := 1024; v_m integer := 512; v_w integer := 112; v_s bit varying := repeat('0', v_n)::bit varying; v_h bit varying[] := array[]::bit varying[]; v_y bit varying; v_row bit varying; v_bytes bytea := ''::bytea; v_params text; v_pos integer; begin for v_pos in select i from generate_series(0, v_n - 1) i order by gen_random_bytes(16) limit v_w loop v_s := set_bit(v_s, v_pos, 1); end loop; for v_pos in 0..v_m - 1 loop v_row := set_bit(repeat('0', v_m)::bit varying, v_pos, 1) || ('x' || encode(gen_random_bytes(v_m / 8), 'hex'))::bit varying; v_h := array_append(v_h, v_row); v_bytes := v_bytes || chat.pack(v_row); end loop; v_y := chat.dot(v_h, v_s); v_params := replace(encode(convert_to(v_n::text || '|' || encode(v_bytes, 'hex') || '|' || v_y::text || '|' || v_w::text, 'UTF8'), 'base64'), E'\n', ''); return jsonb_build_object('n', v_n, 'h', to_jsonb(v_h), 'y', v_y::text, 'w', v_w, 'parameters', v_params, 'verification_id', replace(encode(chat.pack(v_s), 'base64'), E'\n', '')); end; $$; create or replace function chat.valid_response(p_reading billing.reading, p_values text[], p_challenge integer, p_data jsonb) returns boolean language plpgsql immutable as $$ declare v_text text := p_data ->> 'v'; v_v bit varying; v_t bit varying; v_p integer[]; v_a text; v_b text; v_c text; begin if jsonb_typeof(p_data) is distinct from 'object' or v_text is null or length(v_text) <> p_reading.n or v_text !~ '^[01]+$' then return false; end if; if (select count(*) from jsonb_object_keys(p_data)) <> 2 then return false; end if; v_v := v_text::bit varying; if p_challenge in (0, 1) then if jsonb_typeof(p_data -> 'p') is distinct from 'array' then return false; end if; if jsonb_array_length(p_data -> 'p') <> p_reading.n or exists (select 1 from jsonb_array_elements(p_data -> 'p') x where jsonb_typeof(x) <> 'number' or x::text !~ '^(0|[1-9][0-9]{0,4})$') then return false; end if; select array_agg(x::text::integer order by ord) into v_p from jsonb_array_elements(p_data -> 'p') with ordinality as positions(x, ord); if (select count(distinct x) from unnest(v_p) x) <> p_reading.n or (select min(x) from unnest(v_p) x) <> 0 or (select max(x) from unnest(v_p) x) <> p_reading.n - 1 then return false; end if; v_a := chat.hash('a|' || array_to_string(v_p, ',') || '|' || (chat.dot(p_reading.h, v_v) # case when p_challenge = 1 then p_reading.y else repeat('0', bit_length(p_reading.y))::bit varying end)::text); if p_challenge = 0 then v_b := chat.hash('b|' || chat.permute(v_v, v_p)::text); return v_a = p_values[1] and v_b = p_values[2]; end if; v_c := chat.hash('c|' || chat.permute(v_v, v_p)::text); return v_a = p_values[1] and v_c = p_values[3]; elsif p_challenge = 2 then v_text := p_data ->> 't'; if v_text is null or length(v_text) <> p_reading.n or v_text !~ '^[01]+$' then return false; end if; v_t := v_text::bit varying; return bit_count(v_t) = p_reading.w and chat.hash('b|' || v_v::text) = p_values[2] and chat.hash('c|' || (v_v # v_t)::text) = p_values[3]; end if; return false; end; $$; create or replace function chat.check_start(p_reading bigint) returns jsonb language plpgsql as $$ declare v_id uuid; begin perform 1 from billing.reading where id = p_reading and created_at > now() - interval '10 minutes' for key share; if not found then raise exception 'Reading not found.' using errcode = 'P0404'; end if; insert into chat.check_session (reading_id) values (p_reading) returning id into v_id; return jsonb_build_object('id', v_id, 'round', 1, 'stage', 'commit', 'message', 'Step 1 of 10. Submit three values.'); end; $$; create or replace function chat.check_commit(p_id uuid, p_round integer, p_values text[]) returns jsonb language plpgsql as $$ declare v_session chat.check_session; v_challenge integer; begin select * into v_session from chat.check_session where id = p_id for update; if not found then raise exception 'Verification not found.' using errcode = 'P0404'; end if; if v_session.complete or v_session.round <> p_round or v_session.challenge is not null then raise exception 'This step is already complete or awaiting an answer.' using errcode = 'P0409'; end if; if cardinality(p_values) is distinct from 3 or exists (select 1 from unnest(p_values) x where x is null or x !~ '^[0-9a-f]{64}$') then raise exception 'Invalid data format.' using errcode = 'P0400'; end if; v_challenge := chat.challenge(); update chat.check_session set data = p_values, challenge = v_challenge where id = p_id; return jsonb_build_object('round', p_round, 'stage', 'answer', 'challenge', v_challenge, 'message', format('Step %s of 10. Challenge: %s. Submit an answer.', p_round, v_challenge)); end; $$; create or replace function chat.check_answer(p_id uuid, p_round integer, p_data jsonb) returns jsonb language plpgsql as $$ declare v_session chat.check_session; v_reading billing.reading; begin select * into v_session from chat.check_session where id = p_id for update; if not found then raise exception 'Verification not found.' using errcode = 'P0404'; end if; if v_session.complete or v_session.round <> p_round or v_session.challenge is null then raise exception 'This step is already complete or awaiting data.' using errcode = 'P0409'; end if; select * into v_reading from billing.reading where id = v_session.reading_id and created_at > now() - interval '10 minutes'; if not found then delete from chat.check_session where id = p_id; return jsonb_build_object('stage', 'failed', 'message', 'The reading is no longer available.'); end if; if not coalesce(chat.valid_response(v_reading, v_session.data, v_session.challenge, p_data), false) then delete from chat.check_session where id = p_id; return jsonb_build_object('stage', 'failed', 'message', 'Verification failed. Try again.'); end if; if p_round = 10 then update chat.check_session set complete = true, challenge = null, data = null where id = p_id; return jsonb_build_object('stage', 'done', 'reading_id', v_reading.id, 'message', 'Verification complete.', 'reading', jsonb_build_object('id', v_reading.id, 'serial', v_reading.serial, 'kind', v_reading.kind, 'metrics', v_reading.metrics, 'created_at', v_reading.created_at)); end if; update chat.check_session set round = p_round + 1, challenge = null, data = null where id = p_id; return jsonb_build_object('round', p_round + 1, 'stage', 'commit', 'message', format('Step %s of 10. Submit three values.', p_round + 1)); end; $$; drop function if exists chat.check_file(uuid);