@moneypot/hub 1.3.0-dev.3 → 1.3.0-dev.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/config.d.ts +8 -13
- package/dist/src/config.js +78 -52
- package/dist/src/db/index.js +1 -1
- package/dist/src/db/types.d.ts +24 -0
- package/dist/src/db/types.js +5 -1
- package/dist/src/hash-chain/db-hash-chain.d.ts +15 -0
- package/dist/src/hash-chain/db-hash-chain.js +35 -0
- package/dist/src/hash-chain/get-hash.d.ts +17 -0
- package/dist/src/hash-chain/get-hash.js +57 -0
- package/dist/src/hash-chain/plugins/hub-bad-hash-chain-error.d.ts +1 -0
- package/dist/src/hash-chain/plugins/hub-bad-hash-chain-error.js +20 -0
- package/dist/src/hash-chain/plugins/hub-create-hash-chain.d.ts +1 -0
- package/dist/src/hash-chain/plugins/hub-create-hash-chain.js +111 -0
- package/dist/src/hash-chain/plugins/hub-user-active-hash-chain.d.ts +1 -0
- package/dist/src/hash-chain/plugins/hub-user-active-hash-chain.js +46 -0
- package/dist/src/index.js +1 -1
- package/dist/src/pg-advisory-lock.d.ts +9 -4
- package/dist/src/pg-advisory-lock.js +8 -1
- package/dist/src/pg-versions/005-hash-chain.sql +84 -0
- package/dist/src/pg-versions/{005-outcome-bet.sql → 006-outcome-bet.sql} +8 -1
- package/dist/src/plugins/hub-make-outcome-bet.d.ts +8 -1
- package/dist/src/plugins/hub-make-outcome-bet.js +161 -21
- package/dist/src/process-transfers.js +1 -1
- package/dist/src/server/graphile.config.js +7 -1
- package/dist/src/server/handle-errors.js +1 -1
- package/dist/src/server/index.js +1 -1
- package/dist/src/take-request/process-take-request.js +3 -3
- package/package.json +1 -1
package/dist/src/config.d.ts
CHANGED
|
@@ -1,14 +1,9 @@
|
|
|
1
1
|
import "dotenv/config";
|
|
2
|
-
export
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
applicationSecret: string;
|
|
11
|
-
};
|
|
12
|
-
}
|
|
13
|
-
declare const config: Config;
|
|
14
|
-
export default config;
|
|
2
|
+
export declare const NODE_ENV: string;
|
|
3
|
+
export declare const PORT: number;
|
|
4
|
+
export declare const MP_GRAPHQL_URL: string;
|
|
5
|
+
export declare const DATABASE_URL: string;
|
|
6
|
+
export declare const SUPERUSER_DATABASE_URL: string;
|
|
7
|
+
export declare const HASHCHAINSERVER_URL: string;
|
|
8
|
+
export declare const HASHCHAINSERVER_MAX_ITERATIONS: number;
|
|
9
|
+
export declare const HASHCHAINSERVER_APPLICATION_SECRET: string;
|
package/dist/src/config.js
CHANGED
|
@@ -1,57 +1,83 @@
|
|
|
1
1
|
import "dotenv/config";
|
|
2
2
|
import pgConnectionString from "pg-connection-string";
|
|
3
3
|
import { logger } from "./logger.js";
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
logger.warn("Missing NODE_ENV env var. Defaulting to 'development'");
|
|
4
|
+
import { assert } from "tsafe";
|
|
5
|
+
function getEnvVariable(key, transform = (value) => value) {
|
|
6
|
+
return transform(process.env[key] || "");
|
|
8
7
|
}
|
|
9
|
-
|
|
10
|
-
if (!
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
}
|
|
14
|
-
let MP_GRAPHQL_URL = process.env.MP_GRAPHQL_URL || "";
|
|
15
|
-
if (!MP_GRAPHQL_URL) {
|
|
16
|
-
MP_GRAPHQL_URL = "http://localhost:3000/graphql";
|
|
17
|
-
logger.warn(`Missing MP_GRAPHQL_URL env var. Defaulting to ${MP_GRAPHQL_URL}`);
|
|
18
|
-
}
|
|
19
|
-
if (!MP_GRAPHQL_URL.includes("/graphql")) {
|
|
20
|
-
logger.warn(`MP_GRAPHQL_URL didn't include '/graphql'. Are you sure it points to a graphql endpoint?`);
|
|
21
|
-
}
|
|
22
|
-
const DATABASE_URL = process.env.DATABASE_URL || "";
|
|
23
|
-
if (!DATABASE_URL) {
|
|
24
|
-
throw new Error(`Missing DATABASE_URL env var.`);
|
|
25
|
-
}
|
|
26
|
-
const databaseUrlUsername = pgConnectionString.parse(DATABASE_URL).user;
|
|
27
|
-
if (databaseUrlUsername !== "app_postgraphile") {
|
|
28
|
-
logger.warn(`DATABASE_URL username is ${databaseUrlUsername}, expected app_postgraphile`);
|
|
29
|
-
}
|
|
30
|
-
const SUPERUSER_DATABASE_URL = process.env.SUPERUSER_DATABASE_URL || "";
|
|
31
|
-
if (!SUPERUSER_DATABASE_URL) {
|
|
32
|
-
throw new Error("SUPERUSER_DATABASE_URL env var is required");
|
|
33
|
-
}
|
|
34
|
-
const HASHCHAINSERVER_URL = process.env.HASHCHAINSERVER_URL || "mock-server";
|
|
35
|
-
if (HASHCHAINSERVER_URL == "mock-server") {
|
|
36
|
-
logger.warn(`Missing HASHCHAINSERVER_URL env var, defaulting to mock-server.`);
|
|
37
|
-
if (NODE_ENV !== "development") {
|
|
38
|
-
logger.warn("Missing HASHCHAINSERVER_URL and NODE_ENV != 'development': You're using the hashchain mock-server outside of development. (If you aren't using the hashchain server, you can ignore this.)");
|
|
8
|
+
export const NODE_ENV = getEnvVariable("NODE_ENV", (value) => {
|
|
9
|
+
if (!value) {
|
|
10
|
+
logger.warn("Missing NODE_ENV env var. Defaulting to 'development'");
|
|
11
|
+
return "development";
|
|
39
12
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
13
|
+
return value;
|
|
14
|
+
});
|
|
15
|
+
export const PORT = getEnvVariable("PORT", (value) => {
|
|
16
|
+
const parsed = Number.parseInt(value, 10);
|
|
17
|
+
if (!parsed || parsed <= 0 || !Number.isSafeInteger(parsed)) {
|
|
18
|
+
logger.warn("Warning: PORT missing or invalid, defaulting to ", parsed);
|
|
19
|
+
return 4000;
|
|
20
|
+
}
|
|
21
|
+
return parsed;
|
|
22
|
+
});
|
|
23
|
+
export const MP_GRAPHQL_URL = getEnvVariable("MP_GRAPHQL_URL", (value) => {
|
|
24
|
+
if (!value) {
|
|
25
|
+
logger.warn("Missing MP_GRAPHQL_URL env var. Defaulting to http://localhost:3000/graphql");
|
|
26
|
+
return "http://localhost:3000/graphql";
|
|
27
|
+
}
|
|
28
|
+
if (!URL.parse(value)) {
|
|
29
|
+
logger.warn("MP_GRAPHQL_URL is not a valid URL. Defaulting to http://localhost:3000/graphql");
|
|
30
|
+
}
|
|
31
|
+
const url = new URL(value);
|
|
32
|
+
if (url.pathname !== "/graphql") {
|
|
33
|
+
logger.warn("MP_GRAPHQL_URL pathname is not '/graphql'. Are you sure it points to a graphql endpoint?");
|
|
34
|
+
}
|
|
35
|
+
return value;
|
|
36
|
+
});
|
|
37
|
+
export const DATABASE_URL = getEnvVariable("DATABASE_URL", (value) => {
|
|
38
|
+
if (!value) {
|
|
39
|
+
throw new Error(`Missing DATABASE_URL env var.`);
|
|
40
|
+
}
|
|
41
|
+
if (!URL.parse(value)) {
|
|
42
|
+
logger.warn("DATABASE_URL is not a valid URL.");
|
|
43
|
+
}
|
|
44
|
+
const databaseUrlUsername = pgConnectionString.parse(value).user;
|
|
45
|
+
if (databaseUrlUsername !== "app_postgraphile") {
|
|
46
|
+
logger.warn(`DATABASE_URL username is ${databaseUrlUsername}, expected app_postgraphile`);
|
|
47
|
+
}
|
|
48
|
+
return value;
|
|
49
|
+
});
|
|
50
|
+
export const SUPERUSER_DATABASE_URL = getEnvVariable("SUPERUSER_DATABASE_URL", (value) => {
|
|
51
|
+
if (!value) {
|
|
52
|
+
throw new Error("SUPERUSER_DATABASE_URL env var is required");
|
|
53
|
+
}
|
|
54
|
+
if (!URL.parse(value)) {
|
|
55
|
+
logger.warn("SUPERUSER_DATABASE_URL is not a valid URL.");
|
|
56
|
+
}
|
|
57
|
+
return value;
|
|
58
|
+
});
|
|
59
|
+
export const HASHCHAINSERVER_URL = getEnvVariable("HASHCHAINSERVER_URL", (value) => {
|
|
60
|
+
value = value || "mock-server";
|
|
61
|
+
if (value === "mock-server") {
|
|
62
|
+
logger.warn("Using mock-server for HASHCHAINSERVER_URL. This is only allowed in development.");
|
|
63
|
+
}
|
|
64
|
+
else if (!URL.parse(value)) {
|
|
65
|
+
logger.warn("HASHCHAINSERVER_URL is not a valid URL. It can either be empty, 'mock-server', or URL but it was: " +
|
|
66
|
+
value);
|
|
67
|
+
}
|
|
68
|
+
if (NODE_ENV !== "development" && value === "mock-server") {
|
|
69
|
+
logger.warn("Using mock-server for HASHCHAINSERVER_URL. This is only allowed in development.");
|
|
70
|
+
}
|
|
71
|
+
return value;
|
|
72
|
+
});
|
|
73
|
+
export const HASHCHAINSERVER_MAX_ITERATIONS = getEnvVariable("HASHCHAINSERVER_MAX_ITERATIONS", (value) => {
|
|
74
|
+
const iterations = Number.parseInt(value, 10) || 1_000;
|
|
75
|
+
assert(iterations >= 10, "HASHCHAINSERVER_MAX_ITERATIONS must be >= 10");
|
|
76
|
+
return iterations;
|
|
77
|
+
});
|
|
78
|
+
export const HASHCHAINSERVER_APPLICATION_SECRET = getEnvVariable("HASHCHAINSERVER_APPLICATION_SECRET", (value) => {
|
|
79
|
+
if (!value && NODE_ENV !== "development") {
|
|
80
|
+
logger.warn("Missing HASHCHAINSERVER_APPLICATION_SECRET and NODE_ENV != 'development': To use the hashchain server you must pick a random (but stable) HASHCHAINSERVER_APPLICATION_SECRET for secure communciation with it. (If you aren't using the hashchain server, you can ignore this.)");
|
|
81
|
+
}
|
|
82
|
+
return value || "";
|
|
83
|
+
});
|
package/dist/src/db/index.js
CHANGED
package/dist/src/db/types.d.ts
CHANGED
|
@@ -114,3 +114,27 @@ export type DbTakeRequest = {
|
|
|
114
114
|
transfer_completion_attempted_at: Date | null;
|
|
115
115
|
updated_at: Date;
|
|
116
116
|
};
|
|
117
|
+
export type DbHashChain = {
|
|
118
|
+
id: string;
|
|
119
|
+
user_id: string;
|
|
120
|
+
experience_id: string;
|
|
121
|
+
casino_id: string;
|
|
122
|
+
client_seed: string;
|
|
123
|
+
max_iterations: number;
|
|
124
|
+
current_iteration: number;
|
|
125
|
+
active: boolean;
|
|
126
|
+
};
|
|
127
|
+
export declare const DbHashKind: {
|
|
128
|
+
readonly TERMINAL: "TERMINAL";
|
|
129
|
+
readonly INTERMEDIATE: "INTERMEDIATE";
|
|
130
|
+
readonly PREIMAGE: "PREIMAGE";
|
|
131
|
+
};
|
|
132
|
+
export type DbHashKind = (typeof DbHashKind)[keyof typeof DbHashKind];
|
|
133
|
+
export type DbHash = {
|
|
134
|
+
id: string;
|
|
135
|
+
kind: DbHashKind;
|
|
136
|
+
hash_chain_id: string;
|
|
137
|
+
iteration: number;
|
|
138
|
+
digest: Uint8Array;
|
|
139
|
+
metadata: Record<string, unknown>;
|
|
140
|
+
};
|
package/dist/src/db/types.js
CHANGED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { DbCasino, DbExperience, DbHash, DbHashChain, DbUser } from "../db/types.js";
|
|
2
|
+
import { PgClientInTransaction } from "../db/index.js";
|
|
3
|
+
export declare function dbLockHashChain(pgClient: PgClientInTransaction, { userId, experienceId, casinoId, hashChainId, }: {
|
|
4
|
+
userId: DbUser["id"];
|
|
5
|
+
experienceId: DbExperience["id"];
|
|
6
|
+
casinoId: DbCasino["id"];
|
|
7
|
+
hashChainId: DbHashChain["id"];
|
|
8
|
+
}): Promise<DbHashChain | null>;
|
|
9
|
+
export declare function dbInsertHash(pgClient: PgClientInTransaction, { hashChainId, kind, digest, iteration, metadata, }: {
|
|
10
|
+
hashChainId: DbHashChain["id"];
|
|
11
|
+
kind: DbHash["kind"];
|
|
12
|
+
digest: DbHash["digest"];
|
|
13
|
+
iteration: number;
|
|
14
|
+
metadata?: DbHash["metadata"];
|
|
15
|
+
}): Promise<DbHash>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { exactlyOneRow, maybeOneRow, } from "../db/index.js";
|
|
2
|
+
import { assert } from "tsafe";
|
|
3
|
+
export async function dbLockHashChain(pgClient, { userId, experienceId, casinoId, hashChainId, }) {
|
|
4
|
+
assert(pgClient._inTransaction, "dbLockHashChain must be called in a transaction");
|
|
5
|
+
return pgClient
|
|
6
|
+
.query(`
|
|
7
|
+
SELECT *
|
|
8
|
+
FROM hub.hash_chain
|
|
9
|
+
WHERE id = $1
|
|
10
|
+
AND user_id = $2
|
|
11
|
+
AND experience_id = $3
|
|
12
|
+
AND casino_id = $4
|
|
13
|
+
AND active = TRUE
|
|
14
|
+
|
|
15
|
+
FOR UPDATE
|
|
16
|
+
`, [hashChainId, userId, experienceId, casinoId])
|
|
17
|
+
.then(maybeOneRow)
|
|
18
|
+
.then((row) => row ?? null);
|
|
19
|
+
}
|
|
20
|
+
export async function dbInsertHash(pgClient, { hashChainId, kind, digest, iteration, metadata = {}, }) {
|
|
21
|
+
assert(pgClient._inTransaction, "dbInsertHash must be called in a transaction");
|
|
22
|
+
return pgClient
|
|
23
|
+
.query(`
|
|
24
|
+
INSERT INTO hub.hash (hash_chain_id, kind, digest, iteration, metadata)
|
|
25
|
+
VALUES ($1, $2, $3, $4, $5)
|
|
26
|
+
RETURNING *
|
|
27
|
+
`, [
|
|
28
|
+
hashChainId,
|
|
29
|
+
kind,
|
|
30
|
+
digest,
|
|
31
|
+
iteration,
|
|
32
|
+
metadata,
|
|
33
|
+
])
|
|
34
|
+
.then(exactlyOneRow);
|
|
35
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export type HashResult = {
|
|
2
|
+
type: "bad_hash_chain";
|
|
3
|
+
reason: "hashchain_too_old" | "empty_response";
|
|
4
|
+
} | {
|
|
5
|
+
type: "success";
|
|
6
|
+
hash: Uint8Array;
|
|
7
|
+
};
|
|
8
|
+
export declare function getIntermediateHash({ hashChainId, iteration, }: {
|
|
9
|
+
hashChainId: string;
|
|
10
|
+
iteration: number;
|
|
11
|
+
}): Promise<HashResult>;
|
|
12
|
+
export declare function getPreimageHash({ hashChainId, }: {
|
|
13
|
+
hashChainId: string;
|
|
14
|
+
}): Promise<HashResult>;
|
|
15
|
+
export declare function getTerminalHash({ hashChainId, }: {
|
|
16
|
+
hashChainId: string;
|
|
17
|
+
}): Promise<HashResult>;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { getHash } from "@moneypot/hash-herald";
|
|
2
|
+
import * as config from "../config.js";
|
|
3
|
+
const HASH_HERALD_OPTIONS = {
|
|
4
|
+
baseUrl: config.HASHCHAINSERVER_URL,
|
|
5
|
+
applicationSecret: config.HASHCHAINSERVER_APPLICATION_SECRET,
|
|
6
|
+
};
|
|
7
|
+
function resultFromGetHashResponse(response) {
|
|
8
|
+
if (!response.resp) {
|
|
9
|
+
return { type: "bad_hash_chain", reason: "empty_response" };
|
|
10
|
+
}
|
|
11
|
+
const $case = response.resp.$case;
|
|
12
|
+
switch ($case) {
|
|
13
|
+
case "hash":
|
|
14
|
+
return { type: "success", hash: response.resp.value };
|
|
15
|
+
case "hashchainTooOldError":
|
|
16
|
+
return { type: "bad_hash_chain", reason: "hashchain_too_old" };
|
|
17
|
+
default: {
|
|
18
|
+
const _exhaustiveCheck = $case;
|
|
19
|
+
throw new Error(`Unknown hash response: ${_exhaustiveCheck}`);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export async function getIntermediateHash({ hashChainId, iteration, }) {
|
|
24
|
+
const req = {
|
|
25
|
+
hashchainId: hashChainId,
|
|
26
|
+
iterations: iteration,
|
|
27
|
+
context: undefined,
|
|
28
|
+
};
|
|
29
|
+
return getHash(HASH_HERALD_OPTIONS, req).then(resultFromGetHashResponse);
|
|
30
|
+
}
|
|
31
|
+
export async function getPreimageHash({ hashChainId, }) {
|
|
32
|
+
const req = {
|
|
33
|
+
hashchainId: hashChainId,
|
|
34
|
+
iterations: 0,
|
|
35
|
+
context: {
|
|
36
|
+
event: {
|
|
37
|
+
$case: "fetchingPreimage",
|
|
38
|
+
value: {},
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
return getHash(HASH_HERALD_OPTIONS, req).then(resultFromGetHashResponse);
|
|
43
|
+
}
|
|
44
|
+
export async function getTerminalHash({ hashChainId, }) {
|
|
45
|
+
const iterations = 1_000;
|
|
46
|
+
const req = {
|
|
47
|
+
hashchainId: hashChainId,
|
|
48
|
+
iterations,
|
|
49
|
+
context: {
|
|
50
|
+
event: {
|
|
51
|
+
$case: "fetchingTerminalHash",
|
|
52
|
+
value: {},
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
return getHash(HASH_HERALD_OPTIONS, req).then(resultFromGetHashResponse);
|
|
57
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const HubBadHashChainErrorPlugin: GraphileConfig.Plugin;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { ObjectStep, access } from "postgraphile/grafast";
|
|
2
|
+
import { gql, makeExtendSchemaPlugin } from "postgraphile/utils";
|
|
3
|
+
export const HubBadHashChainErrorPlugin = makeExtendSchemaPlugin(() => {
|
|
4
|
+
return {
|
|
5
|
+
typeDefs: gql `
|
|
6
|
+
type HubBadHashChainError {
|
|
7
|
+
message: String
|
|
8
|
+
}
|
|
9
|
+
`,
|
|
10
|
+
plans: {
|
|
11
|
+
HubBadHashChainError: {
|
|
12
|
+
__assertStep: ObjectStep,
|
|
13
|
+
message($data) {
|
|
14
|
+
const $message = access($data, "message");
|
|
15
|
+
return $message;
|
|
16
|
+
},
|
|
17
|
+
},
|
|
18
|
+
},
|
|
19
|
+
};
|
|
20
|
+
}, "HubBadHashChainErrorPlugin");
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const HubCreateHashChainPlugin: GraphileConfig.Plugin;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { context, object, sideEffect } from "@moneypot/hub/grafast";
|
|
2
|
+
import { gql, makeExtendSchemaPlugin } from "@moneypot/hub/graphile";
|
|
3
|
+
import { GraphQLError } from "graphql";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { PgAdvisoryLock } from "../../pg-advisory-lock.js";
|
|
6
|
+
import { exactlyOneRow, superuserPool, withPgPoolTransaction, } from "@moneypot/hub/db";
|
|
7
|
+
import * as HashCommon from "../get-hash.js";
|
|
8
|
+
import { DbHashKind } from "../../db/types.js";
|
|
9
|
+
import * as config from "../../config.js";
|
|
10
|
+
const InputSchema = z.object({
|
|
11
|
+
clientSeed: z.string(),
|
|
12
|
+
});
|
|
13
|
+
export const HubCreateHashChainPlugin = makeExtendSchemaPlugin((build) => {
|
|
14
|
+
const hashChainTable = build.input.pgRegistry.pgResources.hub_hash_chain;
|
|
15
|
+
return {
|
|
16
|
+
typeDefs: gql `
|
|
17
|
+
input HubCreateHashChainInput {
|
|
18
|
+
clientSeed: String!
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type HubCreateHashChainPayload {
|
|
22
|
+
hashChain: HubHashChain!
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
extend type Mutation {
|
|
26
|
+
hubCreateHashChain(
|
|
27
|
+
input: HubCreateHashChainInput!
|
|
28
|
+
): HubCreateHashChainPayload!
|
|
29
|
+
}
|
|
30
|
+
`,
|
|
31
|
+
plans: {
|
|
32
|
+
Mutation: {
|
|
33
|
+
hubCreateHashChain: (_, { $input }) => {
|
|
34
|
+
const $identity = context().get("identity");
|
|
35
|
+
const $hashChainId = sideEffect([$input, $identity], ([rawInput, identity]) => {
|
|
36
|
+
if (identity?.kind !== "user") {
|
|
37
|
+
throw new GraphQLError("Unauthorized");
|
|
38
|
+
}
|
|
39
|
+
const result = InputSchema.safeParse(rawInput);
|
|
40
|
+
if (!result.success) {
|
|
41
|
+
const message = result.error.errors[0].message;
|
|
42
|
+
throw new GraphQLError(message);
|
|
43
|
+
}
|
|
44
|
+
const { clientSeed } = result.data;
|
|
45
|
+
return withPgPoolTransaction(superuserPool, async (pgClient) => {
|
|
46
|
+
await PgAdvisoryLock.forNewHashChain(pgClient, {
|
|
47
|
+
userId: identity.session.user_id,
|
|
48
|
+
experienceId: identity.session.experience_id,
|
|
49
|
+
casinoId: identity.session.casino_id,
|
|
50
|
+
});
|
|
51
|
+
await pgClient.query(`
|
|
52
|
+
UPDATE hub.hash_chain
|
|
53
|
+
SET active = false
|
|
54
|
+
WHERE user_id = $1
|
|
55
|
+
AND experience_id = $2
|
|
56
|
+
AND casino_id = $3
|
|
57
|
+
AND active = true
|
|
58
|
+
`, [
|
|
59
|
+
identity.session.user_id,
|
|
60
|
+
identity.session.experience_id,
|
|
61
|
+
identity.session.casino_id,
|
|
62
|
+
]);
|
|
63
|
+
const dbHashChain = await pgClient
|
|
64
|
+
.query(`
|
|
65
|
+
INSERT INTO hub.hash_chain (
|
|
66
|
+
user_id,
|
|
67
|
+
experience_id,
|
|
68
|
+
casino_id,
|
|
69
|
+
client_seed,
|
|
70
|
+
active,
|
|
71
|
+
max_iteration,
|
|
72
|
+
current_iteration
|
|
73
|
+
)
|
|
74
|
+
VALUES ($1, $2, $3, $4, true, $5, $5)
|
|
75
|
+
RETURNING *
|
|
76
|
+
`, [
|
|
77
|
+
identity.session.user_id,
|
|
78
|
+
identity.session.experience_id,
|
|
79
|
+
identity.session.casino_id,
|
|
80
|
+
clientSeed,
|
|
81
|
+
config.HASHCHAINSERVER_MAX_ITERATIONS,
|
|
82
|
+
])
|
|
83
|
+
.then(exactlyOneRow);
|
|
84
|
+
const terminalHash = await HashCommon.getTerminalHash({
|
|
85
|
+
hashChainId: dbHashChain.id,
|
|
86
|
+
});
|
|
87
|
+
await pgClient.query(`
|
|
88
|
+
INSERT INTO hub.hash (
|
|
89
|
+
hash_chain_id,
|
|
90
|
+
kind,
|
|
91
|
+
digest,
|
|
92
|
+
iteration
|
|
93
|
+
)
|
|
94
|
+
VALUES ($1, $2, $3, $4)
|
|
95
|
+
`, [
|
|
96
|
+
dbHashChain.id,
|
|
97
|
+
DbHashKind.TERMINAL,
|
|
98
|
+
terminalHash,
|
|
99
|
+
config.HASHCHAINSERVER_MAX_ITERATIONS,
|
|
100
|
+
]);
|
|
101
|
+
return dbHashChain.id;
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
return object({
|
|
105
|
+
hashChain: hashChainTable.get({ id: $hashChainId }),
|
|
106
|
+
});
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
},
|
|
110
|
+
};
|
|
111
|
+
}, "CreateHashChainPlugin");
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const HubUserActiveHashChainPlugin: GraphileConfig.Plugin;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { maybeOneRow } from "@moneypot/hub/db";
|
|
2
|
+
import { inhibitOnNull } from "@moneypot/hub/grafast";
|
|
3
|
+
import { context } from "@moneypot/hub/grafast";
|
|
4
|
+
import { gql, makeExtendSchemaPlugin } from "@moneypot/hub/graphile";
|
|
5
|
+
import { withPgClient } from "postgraphile/@dataplan/pg";
|
|
6
|
+
import { object } from "postgraphile/grafast";
|
|
7
|
+
export const HubUserActiveHashChainPlugin = makeExtendSchemaPlugin((build) => {
|
|
8
|
+
const hashChainTable = build.input.pgRegistry.pgResources.hub_hash_chain;
|
|
9
|
+
return {
|
|
10
|
+
typeDefs: gql `
|
|
11
|
+
extend type HubUser {
|
|
12
|
+
activeHashChain: HubHashChain
|
|
13
|
+
}
|
|
14
|
+
`,
|
|
15
|
+
plans: {
|
|
16
|
+
HubUser: {
|
|
17
|
+
activeHashChain: ($record) => {
|
|
18
|
+
const $identity = context().get("identity");
|
|
19
|
+
const $hashChainId = withPgClient(hashChainTable.executor, object({ userId: $record.get("id"), identity: $identity }), async (pgClient, { userId, identity }) => {
|
|
20
|
+
if (identity?.kind !== "user") {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
const { session } = identity;
|
|
24
|
+
const activeHashChain = await pgClient
|
|
25
|
+
.query({
|
|
26
|
+
text: `
|
|
27
|
+
select id
|
|
28
|
+
from hub.hash_chain
|
|
29
|
+
where user_id = $1
|
|
30
|
+
and experience_id = $2
|
|
31
|
+
and casino_id = $3
|
|
32
|
+
and active = TRUE
|
|
33
|
+
order by id desc
|
|
34
|
+
limit 1
|
|
35
|
+
`,
|
|
36
|
+
values: [userId, session.experience_id, session.casino_id],
|
|
37
|
+
})
|
|
38
|
+
.then(maybeOneRow);
|
|
39
|
+
return activeHashChain?.id ?? null;
|
|
40
|
+
});
|
|
41
|
+
return hashChainTable.get({ id: inhibitOnNull($hashChainId) });
|
|
42
|
+
},
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
}, "HubActiveHashChainPlugin");
|
package/dist/src/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import PgUpgradeSchema, { DatabaseAheadError, } from "@moneypot/pg-upgrade-schema";
|
|
2
2
|
import * as db from "./db/index.js";
|
|
3
|
-
import config from "./config.js";
|
|
3
|
+
import * as config from "./config.js";
|
|
4
4
|
import { createHubServer } from "./server/index.js";
|
|
5
5
|
import { initializeTransferProcessors } from "./process-transfers.js";
|
|
6
6
|
import { join } from "path";
|
|
@@ -1,8 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
export declare const
|
|
4
|
-
forMpTakeRequestProcessing: (pgClient:
|
|
1
|
+
import { DbCasino, DbExperience, DbProcessedTakeRequest, DbUser } from "./db/types.js";
|
|
2
|
+
import { PgClientInTransaction } from "./db/index.js";
|
|
3
|
+
export declare const PgAdvisoryLock: {
|
|
4
|
+
forMpTakeRequestProcessing: (pgClient: PgClientInTransaction, params: {
|
|
5
5
|
mpTakeRequestId: DbProcessedTakeRequest["mp_take_request_id"];
|
|
6
6
|
casinoId: DbCasino["id"];
|
|
7
7
|
}) => Promise<void>;
|
|
8
|
+
forNewHashChain: (pgClient: PgClientInTransaction, params: {
|
|
9
|
+
userId: DbUser["id"];
|
|
10
|
+
experienceId: DbExperience["id"];
|
|
11
|
+
casinoId: DbCasino["id"];
|
|
12
|
+
}) => Promise<void>;
|
|
8
13
|
};
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { assert } from "tsafe";
|
|
1
2
|
var LockNamespace;
|
|
2
3
|
(function (LockNamespace) {
|
|
3
4
|
LockNamespace[LockNamespace["MP_TAKE_REQUEST"] = 1] = "MP_TAKE_REQUEST";
|
|
5
|
+
LockNamespace[LockNamespace["NEW_HASH_CHAIN"] = 2] = "NEW_HASH_CHAIN";
|
|
4
6
|
})(LockNamespace || (LockNamespace = {}));
|
|
5
7
|
function simpleHash32(text) {
|
|
6
8
|
let hash = 0;
|
|
@@ -20,8 +22,13 @@ async function acquireAdvisoryLock(pgClient, namespace, hash) {
|
|
|
20
22
|
values: [namespace, hash],
|
|
21
23
|
});
|
|
22
24
|
}
|
|
23
|
-
export const
|
|
25
|
+
export const PgAdvisoryLock = {
|
|
24
26
|
forMpTakeRequestProcessing: async (pgClient, params) => {
|
|
27
|
+
assert(pgClient._inTransaction, "pgClient must be in a transaction");
|
|
25
28
|
await acquireAdvisoryLock(pgClient, LockNamespace.MP_TAKE_REQUEST, createHashKey(params.mpTakeRequestId, params.casinoId));
|
|
26
29
|
},
|
|
30
|
+
forNewHashChain: async (pgClient, params) => {
|
|
31
|
+
assert(pgClient._inTransaction, "pgClient must be in a transaction");
|
|
32
|
+
await acquireAdvisoryLock(pgClient, LockNamespace.NEW_HASH_CHAIN, createHashKey(params.userId, params.experienceId, params.casinoId));
|
|
33
|
+
},
|
|
27
34
|
};
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
CREATE TABLE hub.hash_chain (
|
|
2
|
+
id uuid PRIMARY KEY DEFAULT hub_hidden.uuid_generate_v7(),
|
|
3
|
+
user_id uuid NOT NULL REFERENCES hub.user(id),
|
|
4
|
+
experience_id uuid NOT NULL REFERENCES hub.experience(id),
|
|
5
|
+
casino_id uuid NOT NULL REFERENCES hub.casino(id),
|
|
6
|
+
client_seed text NOT NULL,
|
|
7
|
+
active boolean NOT NULL,
|
|
8
|
+
|
|
9
|
+
max_iteration int NOT NULL check (max_iteration > 0),
|
|
10
|
+
current_iteration int NOT NULL check (current_iteration between 0 and max_iteration)
|
|
11
|
+
);
|
|
12
|
+
|
|
13
|
+
-- TODO: Should probably index current_iteration
|
|
14
|
+
-- CREATE INDEX hash_chain_current_iteration_idx ON hub.hash_chain(current_iteration);
|
|
15
|
+
|
|
16
|
+
CREATE INDEX hash_chain_user_id_idx ON hub.hash_chain(user_id);
|
|
17
|
+
CREATE INDEX hash_chain_experience_id_idx ON hub.hash_chain(experience_id);
|
|
18
|
+
CREATE INDEX hash_chain_casino_id_idx ON hub.hash_chain(casino_id);
|
|
19
|
+
|
|
20
|
+
-- Ensure only one active hash_chain per user per experience per casino
|
|
21
|
+
CREATE UNIQUE INDEX active_hash_chain_idx
|
|
22
|
+
ON hub.hash_chain (user_id, experience_id, casino_id)
|
|
23
|
+
WHERE active = true;
|
|
24
|
+
|
|
25
|
+
CREATE TYPE hub.hash_kind AS ENUM (
|
|
26
|
+
'TERMINAL', -- max iteration hash (e.g. iteration 1000)
|
|
27
|
+
'INTERMEDIATE', -- intermediate hash (e.g. iteration 1-999)
|
|
28
|
+
'PREIMAGE' -- preimage hash (always iteration 0)
|
|
29
|
+
);
|
|
30
|
+
|
|
31
|
+
-- this is the base table for all bets events
|
|
32
|
+
CREATE TABLE hub.hash (
|
|
33
|
+
id uuid PRIMARY KEY DEFAULT hub_hidden.uuid_generate_v7(),
|
|
34
|
+
kind hub.hash_kind NOT NULL,
|
|
35
|
+
hash_chain_id uuid NOT NULL REFERENCES hub.hash_chain(id),
|
|
36
|
+
iteration int NOT NULL check (iteration >= 0), -- which Nth value from the hash chain it is
|
|
37
|
+
digest bytea NOT NULL, -- the actual hash we got from hash chain server
|
|
38
|
+
metadata jsonb NOT NULL DEFAULT '{}' -- operator can store game-specific tags
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
CREATE INDEX hash_hash_chain_id_idx ON hub.hash(hash_chain_id);
|
|
42
|
+
|
|
43
|
+
-- Ensure iterations are unique per hash_chain to avoid dupe mistakes
|
|
44
|
+
CREATE UNIQUE INDEX hash_hash_chain_id_iteration_idx ON hub.hash(hash_chain_id, iteration);
|
|
45
|
+
|
|
46
|
+
-- Ensure a hash_chain only has of each end-type hash
|
|
47
|
+
CREATE UNIQUE INDEX hash_chain_terminal_hash_idx ON hub.hash (hash_chain_id)
|
|
48
|
+
WHERE kind = 'TERMINAL';
|
|
49
|
+
CREATE UNIQUE INDEX hash_chain_preimage_hash_idx ON hub.hash (hash_chain_id)
|
|
50
|
+
WHERE kind = 'PREIMAGE';
|
|
51
|
+
|
|
52
|
+
-- GRANTS
|
|
53
|
+
|
|
54
|
+
GRANT SELECT ON TABLE hub.hash_chain TO app_postgraphile;
|
|
55
|
+
GRANT SELECT ON TABLE hub.hash TO app_postgraphile;
|
|
56
|
+
|
|
57
|
+
-- RLS
|
|
58
|
+
ALTER TABLE hub.hash_chain ENABLE ROW LEVEL SECURITY;
|
|
59
|
+
ALTER TABLE hub.hash ENABLE ROW LEVEL SECURITY;
|
|
60
|
+
|
|
61
|
+
CREATE POLICY select_hash_chain ON hub.hash_chain FOR SELECT USING (
|
|
62
|
+
-- Operator can see all rows
|
|
63
|
+
hub_hidden.is_operator() OR
|
|
64
|
+
-- User can see their own rows
|
|
65
|
+
(
|
|
66
|
+
user_id = hub_hidden.current_user_id() AND
|
|
67
|
+
experience_id = hub_hidden.current_experience_id() AND
|
|
68
|
+
casino_id = hub_hidden.current_casino_id()
|
|
69
|
+
)
|
|
70
|
+
);
|
|
71
|
+
|
|
72
|
+
CREATE POLICY select_hash ON hub.hash FOR SELECT USING (
|
|
73
|
+
-- Operator can see all rows
|
|
74
|
+
hub_hidden.is_operator() OR
|
|
75
|
+
-- User can see their own rows by checking the associated hash_chain
|
|
76
|
+
EXISTS (
|
|
77
|
+
SELECT 1
|
|
78
|
+
FROM hub.hash_chain
|
|
79
|
+
WHERE hub.hash_chain.id = hub.hash.hash_chain_id
|
|
80
|
+
AND hub.hash_chain.user_id = hub_hidden.current_user_id()
|
|
81
|
+
AND hub.hash_chain.experience_id = hub_hidden.current_experience_id()
|
|
82
|
+
AND hub.hash_chain.casino_id = hub_hidden.current_casino_id()
|
|
83
|
+
)
|
|
84
|
+
);
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
drop table if exists hub.outcome_bet cascade;
|
|
2
|
+
drop type if exists hub.outcome cascade;
|
|
3
|
+
|
|
1
4
|
create type hub.outcome as (
|
|
2
5
|
weight float,
|
|
3
6
|
profit float
|
|
@@ -14,6 +17,9 @@ create table hub.outcome_bet (
|
|
|
14
17
|
experience_id uuid not null references hub.experience(id),
|
|
15
18
|
casino_id uuid not null references hub.casino(id),
|
|
16
19
|
|
|
20
|
+
-- provably fair hash chain
|
|
21
|
+
hash_chain_id uuid not null references hub.hash_chain(id),
|
|
22
|
+
|
|
17
23
|
currency_key text not null,
|
|
18
24
|
wager float not null,
|
|
19
25
|
|
|
@@ -24,7 +30,7 @@ create table hub.outcome_bet (
|
|
|
24
30
|
profit float not null,
|
|
25
31
|
|
|
26
32
|
-- null when no outcomes saved
|
|
27
|
-
outcome_idx smallint null,
|
|
33
|
+
outcome_idx smallint null check (outcome_idx between 0 and array_length(outcomes,1)-1),
|
|
28
34
|
outcomes hub.outcome[] not null default '{}',
|
|
29
35
|
|
|
30
36
|
-- Operator-provided data per bet
|
|
@@ -37,6 +43,7 @@ create index outcome_bet_user_id_idx on hub.outcome_bet(user_id);
|
|
|
37
43
|
create index outcome_bet_experience_id_idx on hub.outcome_bet(experience_id);
|
|
38
44
|
create index outcome_bet_casino_id_idx on hub.outcome_bet(casino_id);
|
|
39
45
|
create index outcome_bet_kind_idx on hub.outcome_bet(kind);
|
|
46
|
+
create index outcome_bet_hash_chain_id_idx on hub.outcome_bet(hash_chain_id);
|
|
40
47
|
|
|
41
48
|
-- GRANT
|
|
42
49
|
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import { Result } from "../util.js";
|
|
2
3
|
declare const InputSchema: z.ZodObject<{
|
|
3
4
|
kind: z.ZodString;
|
|
4
5
|
wager: z.ZodNumber;
|
|
@@ -25,28 +26,34 @@ declare const InputSchema: z.ZodObject<{
|
|
|
25
26
|
weight: number;
|
|
26
27
|
profit: number;
|
|
27
28
|
}[]>;
|
|
29
|
+
hashChainId: z.ZodString;
|
|
30
|
+
metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
28
31
|
}, "strict", z.ZodTypeAny, {
|
|
29
32
|
currency: string;
|
|
30
33
|
kind: string;
|
|
34
|
+
hashChainId: string;
|
|
31
35
|
wager: number;
|
|
32
36
|
outcomes: {
|
|
33
37
|
weight: number;
|
|
34
38
|
profit: number;
|
|
35
39
|
}[];
|
|
40
|
+
metadata?: Record<string, any> | undefined;
|
|
36
41
|
}, {
|
|
37
42
|
currency: string;
|
|
38
43
|
kind: string;
|
|
44
|
+
hashChainId: string;
|
|
39
45
|
wager: number;
|
|
40
46
|
outcomes: {
|
|
41
47
|
weight: number;
|
|
42
48
|
profit: number;
|
|
43
49
|
}[];
|
|
50
|
+
metadata?: Record<string, any> | undefined;
|
|
44
51
|
}>;
|
|
45
52
|
type Input = z.infer<typeof InputSchema>;
|
|
46
53
|
export type OutcomeBetConfig = {
|
|
47
54
|
houseEdge: number;
|
|
48
55
|
saveOutcomes: boolean;
|
|
49
|
-
|
|
56
|
+
processMetadata?: (input: Input) => Result<Record<string, any>, string>;
|
|
50
57
|
};
|
|
51
58
|
export type OutcomeBetConfigMap<BetKind extends string> = {
|
|
52
59
|
[betKind in BetKind]: OutcomeBetConfig;
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import { context, object, sideEffect } from "postgraphile/grafast";
|
|
1
|
+
import { access, context, object, ObjectStep, polymorphicBranch, sideEffect, } from "postgraphile/grafast";
|
|
2
2
|
import { gql, makeExtendSchemaPlugin } from "postgraphile/utils";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
import { GraphQLError } from "graphql";
|
|
5
|
-
import { exactlyOneRow, maybeOneRow, superuserPool, withPgPoolTransaction, } from "../db/index.js";
|
|
5
|
+
import { DbHashKind, exactlyOneRow, maybeOneRow, superuserPool, withPgPoolTransaction, } from "../db/index.js";
|
|
6
6
|
import { assert } from "tsafe";
|
|
7
|
+
import { dbInsertHash, dbLockHashChain } from "../hash-chain/db-hash-chain.js";
|
|
8
|
+
import { getIntermediateHash, getPreimageHash, } from "../hash-chain/get-hash.js";
|
|
7
9
|
const FLOAT_EPSILON = 1e-10;
|
|
8
10
|
function sum(ns) {
|
|
9
11
|
return ns.reduce((a, b) => a + b, 0);
|
|
@@ -35,6 +37,8 @@ const InputSchema = z
|
|
|
35
37
|
.max(50, "Outcome count must be <= 50")
|
|
36
38
|
.refine((data) => data.some((o) => o.profit < 0), "At least one outcome should have profit < 0")
|
|
37
39
|
.refine((data) => data.some((o) => o.profit > 0), "At least one outcome should have profit > 0"),
|
|
40
|
+
hashChainId: z.string().uuid("Invalid hash chain ID"),
|
|
41
|
+
metadata: z.record(z.string(), z.any()).optional(),
|
|
38
42
|
})
|
|
39
43
|
.strict();
|
|
40
44
|
const BetKindSchema = z
|
|
@@ -48,7 +52,7 @@ const BetConfigsSchema = z.record(BetKindSchema, z.object({
|
|
|
48
52
|
.gte(0, "House edge must be >= 0")
|
|
49
53
|
.lte(1, "House edge must be <= 1"),
|
|
50
54
|
saveOutcomes: z.boolean(),
|
|
51
|
-
|
|
55
|
+
processMetadata: z
|
|
52
56
|
.function()
|
|
53
57
|
.args(InputSchema)
|
|
54
58
|
.returns(z.record(z.string(), z.any()))
|
|
@@ -69,12 +73,20 @@ export function MakeOutcomeBetPlugin({ betConfigs }) {
|
|
|
69
73
|
wager: Int!
|
|
70
74
|
currency: String!
|
|
71
75
|
outcomes: [HubOutcomeInput!]!
|
|
76
|
+
hashChainId: UUID!
|
|
77
|
+
metadata: JSON
|
|
72
78
|
}
|
|
73
79
|
|
|
74
|
-
type
|
|
80
|
+
type HubMakeOutcomeBetOk {
|
|
75
81
|
bet: HubOutcomeBet!
|
|
76
82
|
}
|
|
77
83
|
|
|
84
|
+
union HubMakeOutcomeBetResult = HubMakeOutcomeBetOk | HubBadHashChainError
|
|
85
|
+
|
|
86
|
+
type HubMakeOutcomeBetPayload {
|
|
87
|
+
result: HubMakeOutcomeBetResult!
|
|
88
|
+
}
|
|
89
|
+
|
|
78
90
|
extend type Mutation {
|
|
79
91
|
hubMakeOutcomeBet(input: HubMakeOutcomeBetInput!): HubMakeOutcomeBetPayload
|
|
80
92
|
}
|
|
@@ -85,7 +97,7 @@ export function MakeOutcomeBetPlugin({ betConfigs }) {
|
|
|
85
97
|
Mutation: {
|
|
86
98
|
hubMakeOutcomeBet: (_, { $input }) => {
|
|
87
99
|
const $identity = context().get("identity");
|
|
88
|
-
const $
|
|
100
|
+
const $result = sideEffect([$identity, $input], async ([identity, rawInput]) => {
|
|
89
101
|
if (identity?.kind !== "user") {
|
|
90
102
|
throw new GraphQLError("Unauthorized");
|
|
91
103
|
}
|
|
@@ -108,6 +120,16 @@ export function MakeOutcomeBetPlugin({ betConfigs }) {
|
|
|
108
120
|
if (!betKinds.includes(rawInput.kind)) {
|
|
109
121
|
throw new GraphQLError(`Invalid bet kind`);
|
|
110
122
|
}
|
|
123
|
+
let validatedMetadata;
|
|
124
|
+
if (betConfig.processMetadata) {
|
|
125
|
+
const result = betConfig.processMetadata(input);
|
|
126
|
+
if (result.ok) {
|
|
127
|
+
validatedMetadata = result.value;
|
|
128
|
+
}
|
|
129
|
+
else {
|
|
130
|
+
throw new GraphQLError(`Invalid metadata: ${result.error}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
111
133
|
const houseEV = calculateHouseEV(input.outcomes);
|
|
112
134
|
const minHouseEV = Math.max(0, betConfig.houseEdge - FLOAT_EPSILON);
|
|
113
135
|
if (houseEV < minHouseEV) {
|
|
@@ -158,7 +180,65 @@ export function MakeOutcomeBetPlugin({ betConfigs }) {
|
|
|
158
180
|
if (maxPotentialPayout > maxAllowablePayout) {
|
|
159
181
|
throw new GraphQLError(`House risk limit exceeded. Max payout: ${maxPotentialPayout.toFixed(4)}`);
|
|
160
182
|
}
|
|
161
|
-
const
|
|
183
|
+
const dbHashChain = await dbLockHashChain(pgClient, {
|
|
184
|
+
userId: session.user_id,
|
|
185
|
+
experienceId: session.experience_id,
|
|
186
|
+
casinoId: session.casino_id,
|
|
187
|
+
hashChainId: input.hashChainId,
|
|
188
|
+
});
|
|
189
|
+
if (!dbHashChain || !dbHashChain.active) {
|
|
190
|
+
return {
|
|
191
|
+
__typename: "HubBadHashChainError",
|
|
192
|
+
message: "Active hash chain not found",
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
if (dbHashChain.current_iteration <= 1) {
|
|
196
|
+
if (dbHashChain.current_iteration === 1) {
|
|
197
|
+
finishHashChainInBackground({
|
|
198
|
+
hashChainId: input.hashChainId,
|
|
199
|
+
}).catch((e) => {
|
|
200
|
+
console.error("Error finishing hash chain in background", { hashChainId: input.hashChainId, error: e });
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
return {
|
|
204
|
+
__typename: "HubBadHashChainError",
|
|
205
|
+
message: "Hash chain drained. Create a new one.",
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
const betHashIteration = dbHashChain.current_iteration - 1;
|
|
209
|
+
assert(betHashIteration > 0, "Bet hash iteration must be > 0");
|
|
210
|
+
const betHashResult = await getIntermediateHash({
|
|
211
|
+
hashChainId: input.hashChainId,
|
|
212
|
+
iteration: betHashIteration,
|
|
213
|
+
});
|
|
214
|
+
switch (betHashResult.type) {
|
|
215
|
+
case "success":
|
|
216
|
+
break;
|
|
217
|
+
case "bad_hash_chain":
|
|
218
|
+
return {
|
|
219
|
+
__typename: "HubBadHashChainError",
|
|
220
|
+
message: "Hash chain not found",
|
|
221
|
+
};
|
|
222
|
+
default: {
|
|
223
|
+
const _exhaustiveCheck = betHashResult;
|
|
224
|
+
throw new Error(`Unknown bet hash result: ${_exhaustiveCheck}`);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
await dbInsertHash(pgClient, {
|
|
228
|
+
hashChainId: dbHashChain.id,
|
|
229
|
+
kind: DbHashKind.INTERMEDIATE,
|
|
230
|
+
digest: betHashResult.hash,
|
|
231
|
+
iteration: betHashIteration,
|
|
232
|
+
});
|
|
233
|
+
const result = await pgClient.query(`
|
|
234
|
+
UPDATE hub.hash_chain
|
|
235
|
+
SET current_iteration = $2
|
|
236
|
+
WHERE id = $1
|
|
237
|
+
`, [dbHashChain.id, betHashIteration]);
|
|
238
|
+
if (result.rowCount !== 1) {
|
|
239
|
+
throw new GraphQLError("Failed to update hash chain iteration");
|
|
240
|
+
}
|
|
241
|
+
const { outcome, outcomeIdx } = pickRandomOutcome(input.outcomes, betHashResult.hash);
|
|
162
242
|
const netPlayerAmount = input.wager * outcome.profit;
|
|
163
243
|
await pgClient.query({
|
|
164
244
|
text: `
|
|
@@ -198,12 +278,11 @@ export function MakeOutcomeBetPlugin({ betConfigs }) {
|
|
|
198
278
|
wager: input.wager,
|
|
199
279
|
profit: outcome.profit,
|
|
200
280
|
currency_key: dbCurrency.key,
|
|
281
|
+
hash_chain_id: input.hashChainId,
|
|
201
282
|
user_id: session.user_id,
|
|
202
283
|
casino_id: session.casino_id,
|
|
203
284
|
experience_id: session.experience_id,
|
|
204
|
-
metadata:
|
|
205
|
-
? await betConfig.getMetadata(input)
|
|
206
|
-
: {},
|
|
285
|
+
metadata: validatedMetadata,
|
|
207
286
|
...(betConfig.saveOutcomes
|
|
208
287
|
? {
|
|
209
288
|
outcomes: input.outcomes,
|
|
@@ -221,6 +300,7 @@ export function MakeOutcomeBetPlugin({ betConfigs }) {
|
|
|
221
300
|
user_id,
|
|
222
301
|
casino_id,
|
|
223
302
|
experience_id,
|
|
303
|
+
hash_chain_id,
|
|
224
304
|
kind,
|
|
225
305
|
currency_key,
|
|
226
306
|
wager,
|
|
@@ -229,13 +309,14 @@ export function MakeOutcomeBetPlugin({ betConfigs }) {
|
|
|
229
309
|
outcome_idx,
|
|
230
310
|
metadata
|
|
231
311
|
)
|
|
232
|
-
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
|
312
|
+
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
|
|
233
313
|
RETURNING id
|
|
234
314
|
`,
|
|
235
315
|
values: [
|
|
236
316
|
newBet.user_id,
|
|
237
317
|
newBet.casino_id,
|
|
238
318
|
newBet.experience_id,
|
|
319
|
+
newBet.hash_chain_id,
|
|
239
320
|
newBet.kind,
|
|
240
321
|
newBet.currency_key,
|
|
241
322
|
newBet.wager,
|
|
@@ -246,11 +327,31 @@ export function MakeOutcomeBetPlugin({ betConfigs }) {
|
|
|
246
327
|
],
|
|
247
328
|
})
|
|
248
329
|
.then(exactlyOneRow);
|
|
249
|
-
return
|
|
330
|
+
return {
|
|
331
|
+
__typename: "HubMakeOutcomeBetOk",
|
|
332
|
+
betId: bet.id,
|
|
333
|
+
};
|
|
250
334
|
});
|
|
251
335
|
});
|
|
252
336
|
return object({
|
|
253
|
-
|
|
337
|
+
result: $result,
|
|
338
|
+
});
|
|
339
|
+
},
|
|
340
|
+
},
|
|
341
|
+
HubMakeOutcomeBetOk: {
|
|
342
|
+
__assertStep: ObjectStep,
|
|
343
|
+
bet($data) {
|
|
344
|
+
const $betId = access($data, "betId");
|
|
345
|
+
return outcomeBetTable.get({ id: $betId });
|
|
346
|
+
},
|
|
347
|
+
},
|
|
348
|
+
HubMakeOutcomeBetPayload: {
|
|
349
|
+
__assertStep: ObjectStep,
|
|
350
|
+
result($data) {
|
|
351
|
+
const $result = $data.get("result");
|
|
352
|
+
return polymorphicBranch($result, {
|
|
353
|
+
HubMakeOutcomeBetOk: {},
|
|
354
|
+
HubBadHashChainError: {},
|
|
254
355
|
});
|
|
255
356
|
},
|
|
256
357
|
},
|
|
@@ -258,12 +359,13 @@ export function MakeOutcomeBetPlugin({ betConfigs }) {
|
|
|
258
359
|
};
|
|
259
360
|
}, "HubMakeOutcomeBetPlugin");
|
|
260
361
|
}
|
|
261
|
-
function
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
362
|
+
function normalizeHash(hash) {
|
|
363
|
+
assert(hash.length >= 4, "Hash must be at least 4 bytes");
|
|
364
|
+
const view = new DataView(hash.buffer, hash.byteOffset, Math.min(hash.byteLength, 4));
|
|
365
|
+
const uint32Value = view.getUint32(0, false);
|
|
366
|
+
return uint32Value / Math.pow(2, 32);
|
|
265
367
|
}
|
|
266
|
-
function pickRandomOutcome(outcomes) {
|
|
368
|
+
function pickRandomOutcome(outcomes, hash) {
|
|
267
369
|
assert(outcomes.length >= 2, "Outcome count must be >= 2");
|
|
268
370
|
const totalWeight = sum(outcomes.map((o) => o.weight));
|
|
269
371
|
const outcomesWithProbability = outcomes.map((o) => ({
|
|
@@ -272,12 +374,12 @@ function pickRandomOutcome(outcomes) {
|
|
|
272
374
|
}));
|
|
273
375
|
const totalProb = outcomesWithProbability.reduce((sum, outcome) => sum + outcome.probability, 0);
|
|
274
376
|
assert(Math.abs(totalProb - 1.0) < FLOAT_EPSILON, "Probabilities must sum to ~1");
|
|
275
|
-
const randomValue =
|
|
276
|
-
let
|
|
377
|
+
const randomValue = normalizeHash(hash);
|
|
378
|
+
let cumulativeProb = 0;
|
|
277
379
|
for (let i = 0; i < outcomesWithProbability.length; i++) {
|
|
278
380
|
const outcome = outcomesWithProbability[i];
|
|
279
|
-
|
|
280
|
-
if (randomValue <=
|
|
381
|
+
cumulativeProb += outcome.probability;
|
|
382
|
+
if (randomValue <= cumulativeProb) {
|
|
281
383
|
return { outcome, outcomeIdx: i };
|
|
282
384
|
}
|
|
283
385
|
}
|
|
@@ -323,3 +425,41 @@ async function dbLockBalanceAndBankroll(pgClient, { userId, casinoId, experience
|
|
|
323
425
|
dbHouseBankroll: null,
|
|
324
426
|
};
|
|
325
427
|
}
|
|
428
|
+
async function finishHashChainInBackground({ hashChainId, }) {
|
|
429
|
+
console.log("Finishing hash chain in background", { hashChainId });
|
|
430
|
+
const preimageHashResult = await getPreimageHash({
|
|
431
|
+
hashChainId,
|
|
432
|
+
});
|
|
433
|
+
console.log("Preimage hash result", { preimageHashResult });
|
|
434
|
+
if (preimageHashResult.type === "success") {
|
|
435
|
+
console.log("Inserting preimage hash", {
|
|
436
|
+
hashChainId,
|
|
437
|
+
kind: DbHashKind.PREIMAGE,
|
|
438
|
+
digest: preimageHashResult.hash,
|
|
439
|
+
iteration: 0,
|
|
440
|
+
});
|
|
441
|
+
await withPgPoolTransaction(superuserPool, async (pgClient) => {
|
|
442
|
+
await dbInsertHash(pgClient, {
|
|
443
|
+
hashChainId,
|
|
444
|
+
kind: DbHashKind.PREIMAGE,
|
|
445
|
+
digest: preimageHashResult.hash,
|
|
446
|
+
iteration: 0,
|
|
447
|
+
});
|
|
448
|
+
const result = await pgClient.query(`
|
|
449
|
+
UPDATE hub.hash_chain
|
|
450
|
+
SET current_iteration = 0,
|
|
451
|
+
active = false
|
|
452
|
+
WHERE id = $1
|
|
453
|
+
`, [hashChainId]);
|
|
454
|
+
if (result.rowCount !== 1) {
|
|
455
|
+
throw new Error("Failed to update hash chain iteration");
|
|
456
|
+
}
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
else {
|
|
460
|
+
console.warn("Failed to insert preimage hash in background", {
|
|
461
|
+
hashChainId,
|
|
462
|
+
error: preimageHashResult,
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
}
|
|
@@ -6,7 +6,7 @@ import EventEmitter from "events";
|
|
|
6
6
|
import { superuserPool } from "./db/index.js";
|
|
7
7
|
import { dbGetCasinoById, dbGetCasinoSecretById } from "./db/internal.js";
|
|
8
8
|
import pg from "pg";
|
|
9
|
-
import config from "./config.js";
|
|
9
|
+
import * as config from "./config.js";
|
|
10
10
|
import { z } from "zod";
|
|
11
11
|
import { gql } from "./__generated__/gql.js";
|
|
12
12
|
import { logger } from "./logger.js";
|
|
@@ -2,7 +2,7 @@ import "graphile-config";
|
|
|
2
2
|
import "postgraphile";
|
|
3
3
|
import { makePgService } from "postgraphile/adaptors/pg";
|
|
4
4
|
import { PostGraphileAmberPreset } from "postgraphile/presets/amber";
|
|
5
|
-
import config from "../config.js";
|
|
5
|
+
import * as config from "../config.js";
|
|
6
6
|
import { maskError } from "./handle-errors.js";
|
|
7
7
|
import * as db from "../db/index.js";
|
|
8
8
|
import { SmartTagsPlugin } from "../smart-tags.js";
|
|
@@ -20,6 +20,9 @@ import { HubAddCasinoPlugin } from "../plugins/hub-add-casino.js";
|
|
|
20
20
|
import { HubBalanceAlertPlugin } from "../plugins/hub-balance-alert.js";
|
|
21
21
|
import { custom as customPgOmitArchivedPlugin } from "@graphile-contrib/pg-omit-archived";
|
|
22
22
|
import { HubCurrentXPlugin } from "../plugins/hub-current-x.js";
|
|
23
|
+
import { HubCreateHashChainPlugin } from "../hash-chain/plugins/hub-create-hash-chain.js";
|
|
24
|
+
import { HubBadHashChainErrorPlugin } from "../hash-chain/plugins/hub-bad-hash-chain-error.js";
|
|
25
|
+
import { HubUserActiveHashChainPlugin } from "../hash-chain/plugins/hub-user-active-hash-chain.js";
|
|
23
26
|
export const requiredPlugins = [
|
|
24
27
|
SmartTagsPlugin,
|
|
25
28
|
IdToNodeIdPlugin,
|
|
@@ -35,6 +38,9 @@ export const requiredPlugins = [
|
|
|
35
38
|
export const defaultPlugins = [
|
|
36
39
|
...(config.NODE_ENV === "development" ? [DebugPlugin] : []),
|
|
37
40
|
...requiredPlugins,
|
|
41
|
+
HubBadHashChainErrorPlugin,
|
|
42
|
+
HubCreateHashChainPlugin,
|
|
43
|
+
HubUserActiveHashChainPlugin,
|
|
38
44
|
HubClaimFaucetPlugin,
|
|
39
45
|
customPgOmitArchivedPlugin("deleted"),
|
|
40
46
|
];
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { GraphQLError } from "postgraphile/graphql";
|
|
2
|
-
import config from "../config.js";
|
|
2
|
+
import * as config from "../config.js";
|
|
3
3
|
const isDev = config.NODE_ENV === "development";
|
|
4
4
|
const isTest = config.NODE_ENV === "test";
|
|
5
5
|
const camelCase = (s) => s.toLowerCase().replace(/(_\\w)/g, (m) => m[1].toUpperCase());
|
package/dist/src/server/index.js
CHANGED
|
@@ -3,7 +3,7 @@ import { grafserv } from "grafserv/express/v4";
|
|
|
3
3
|
import postgraphile from "postgraphile";
|
|
4
4
|
import { createPreset, defaultPlugins } from "./graphile.config.js";
|
|
5
5
|
import express from "express";
|
|
6
|
-
import config from "../config.js";
|
|
6
|
+
import * as config from "../config.js";
|
|
7
7
|
import { logger } from "../logger.js";
|
|
8
8
|
import cors from "./middleware/cors.js";
|
|
9
9
|
import authentication from "./middleware/authentication.js";
|
|
@@ -2,7 +2,7 @@ import { gql } from "../__generated__/gql.js";
|
|
|
2
2
|
import { TakeRequestStatus as MpTakeRequestStatus, TransferStatusKind as MpTransferStatus, } from "../__generated__/graphql.js";
|
|
3
3
|
import { exactlyOneRow, maybeOneRow, superuserPool, withPgPoolTransaction, } from "../db/index.js";
|
|
4
4
|
import { assert } from "tsafe";
|
|
5
|
-
import {
|
|
5
|
+
import { PgAdvisoryLock } from "../pg-advisory-lock.js";
|
|
6
6
|
const MP_PAGINATE_PENDING_TAKE_REQUESTS = gql(`
|
|
7
7
|
query MpPaginatedPendingTakeRequests($controllerId: UUID!, $after: Cursor) {
|
|
8
8
|
allTakeRequests(
|
|
@@ -178,7 +178,7 @@ async function fetchPendingTakeRequests(graphqlClient, controllerId) {
|
|
|
178
178
|
}
|
|
179
179
|
async function processSingleTakeRequest({ mpTakeRequestId, mpTakeRequest, casinoId, graphqlClient, }) {
|
|
180
180
|
return withPgPoolTransaction(superuserPool, async (pgClient) => {
|
|
181
|
-
await
|
|
181
|
+
await PgAdvisoryLock.forMpTakeRequestProcessing(pgClient, {
|
|
182
182
|
mpTakeRequestId,
|
|
183
183
|
casinoId,
|
|
184
184
|
});
|
|
@@ -457,7 +457,7 @@ async function processPendingTransferCompletions({ casinoId, graphqlClient, abor
|
|
|
457
457
|
}
|
|
458
458
|
async function completeTransfer({ mpTakeRequestId, takeRequestId, mpTransferId, graphqlClient, casinoId, }) {
|
|
459
459
|
return withPgPoolTransaction(superuserPool, async (pgClient) => {
|
|
460
|
-
await
|
|
460
|
+
await PgAdvisoryLock.forMpTakeRequestProcessing(pgClient, {
|
|
461
461
|
mpTakeRequestId,
|
|
462
462
|
casinoId,
|
|
463
463
|
});
|