Added signing for genesis block

This commit is contained in:
QiTao Weng 2021-04-10 09:12:48 +00:00
parent 9e4821c296
commit 025bc58869

View File

@ -1,5 +1,5 @@
import { Singleton, Inject } from "@extollo/di"
import {Unit, Logging, Config} from "@extollo/lib"
import { Unit, Logging, Config, Application } from "@extollo/lib"
import { FirebaseUnit } from "./FirebaseUnit"
import { BlockEncounterTransaction, BlockResource, BlockResourceItem, BlockTransaction } from "../rtdb/BlockResource"
import { TransactionResourceItem } from "../rtdb/TransactionResource"
@ -19,7 +19,9 @@ export class Block implements BlockResourceItem {
lastBlockHash: string;
lastBlockUUID: string;
proof: string;
get config(): Config {
return Application.getApplication().make(Config)
}
constructor(rec: BlockResourceItem) {
this.firebaseID = rec.firebaseID;
this.seqID = rec.seqID
@ -32,9 +34,22 @@ export class Block implements BlockResourceItem {
}
/** Returns true if this is the genesis block. */
isGenesis() {
// FIXME sign this with GPG to verify that it came from here
return this.uuid === '0000'
async isGenesis() {
// first block will be guaranteed uuid 0000
if (this.uuid !== '0000') {
return false;
}
const proof = this.proof
const publicKey = this.config.get("app.gpg.key.public")
const message = openpgp.Message.fromText(proof)
// Verify the signature
const verified = await (await openpgp.verify({
message,
publicKeys: publicKey
})).signatures[0].verified
return !!verified
}
/** Generate the hash for this block. */
@ -127,10 +142,7 @@ export class Blockchain extends Unit {
*/
public async validate(chain: Block[]) {
const blocks = collect<Block>(chain)
return blocks.every((block: Block, idx: number) => {
if ( idx === 0 ) return block.isGenesis()
return block.lastBlockHash === blocks.at(idx)!.hash()
})
return (await blocks.promiseMap((block: Block) => block.isGenesis())).every(Boolean)
}
public async refresh() {
@ -163,14 +175,19 @@ export class Blockchain extends Unit {
/**
* Instantiate the genesis block of the entire chain.
*/
public getGenesisBlock(): Block {
public async getGenesisBlock(): Promise<Block> {
const message = openpgp.Message.fromText("0000")
const privateKey = this.config.get("app.gpg.key.private")
return new Block({
timestamp: (new Date).getTime(),
uuid: '0000',
transactions: [],
lastBlockHash: '',
lastBlockUUID: '',
proof: '',
proof: (await openpgp.sign({
message,
privateKeys: privateKey
})).toString(),
firebaseID: '',
seqID: -1,
})
@ -183,7 +200,7 @@ export class Blockchain extends Unit {
const rec: BlockResourceItem | undefined = await BlockResource.collect().last()
if (rec) return new Block(rec)
const genesis = this.getGenesisBlock().toItem()
const genesis = (await this.getGenesisBlock()).toItem()
await (<BlockResource>this.app().make(BlockResource)).push(genesis)
return this.getLastBlock()
}