loc-chain-backend/src/app/rtdb/BlockResource.ts

73 lines
2.4 KiB
TypeScript
Raw Normal View History

2021-04-10 07:01:57 +00:00
import {FirebaseResource, FirebaseResourceItem} from "../FirebaseResource"
import {Injectable} from "@extollo/di"
import {RTDBRef} from "../units/FirebaseUnit"
import {AsyncCollection} from "@extollo/util"
2021-04-10 08:44:56 +00:00
/**
* A block transaction representing an encounter between two clients.
*/
2021-04-10 07:01:57 +00:00
export interface BlockEncounterTransaction {
combinedHash: string;
timestamp: number;
encodedGPSLocation: string;
}
2021-04-10 08:44:56 +00:00
/**
* A block transaction representing an infected client.
*/
2021-04-10 07:01:57 +00:00
export interface BlockInfectionTransaction {
clientID: string;
timestamp: number;
}
2021-04-10 08:44:56 +00:00
/** Union type of all possible block transactions. */
2021-04-10 07:01:57 +00:00
export type BlockTransaction = BlockInfectionTransaction | BlockEncounterTransaction
/** Returns true if the item is a valid BlockEncounterTransaction. */
2021-04-10 07:01:57 +00:00
export function isBlockEncounterTransaction(what: any): what is BlockEncounterTransaction {
return (
what
&& typeof what.combinedHash === 'string'
&& typeof what.timestamp === 'number'
&& typeof what.encodedGPSLocation === 'string'
)
}
/** Returns true if the item is a valid BlockInfectionTransaction. */
2021-04-10 07:01:57 +00:00
export function isBlockInfectionTransaction(what: any): what is BlockInfectionTransaction {
return (
what
&& typeof what.clientID === 'string'
&& typeof what.timestamp === 'number'
)
}
/** Returns true if the item is a valid BlockTransaction. */
2021-04-10 07:01:57 +00:00
export function isBlockTransaction(what: any): what is BlockTransaction {
return isBlockEncounterTransaction(what) || isBlockInfectionTransaction(what)
}
2021-04-10 08:44:56 +00:00
/**
* Interface representing a single block in the chain.
*/
2021-04-10 07:01:57 +00:00
export interface BlockResourceItem extends FirebaseResourceItem {
uuid: string; // Globally unique ID
transactions: BlockTransaction[]; // Transactions validated by this block
lastBlockHash: string; // The combined sha256 hash of the previous block
lastBlockUUID: string; // the UUID of the previous block
proof: string; // the generated proof-of-work string
timestamp: number; // millisecond unix timestamp when this block was created
2021-04-10 07:01:57 +00:00
}
/**
* A Firebase realtime database resource for blocks in the chain.
*/
2021-04-10 07:01:57 +00:00
@Injectable()
export class BlockResource extends FirebaseResource<BlockResourceItem> {
public static collect(): AsyncCollection<BlockResourceItem> {
return new AsyncCollection<BlockResourceItem>(new BlockResource())
}
protected refName: RTDBRef = 'block'
}